python操作RabbitMQ实现数据发送和接收

python的pika库

import pika
import json
import os.path
import pickle
import datetime
import time



# 发送消息
def push(result_list):
   
    # 虚拟队列需要指定参数 virtual_host,如果是默认的可以不填。
    credentials = pika.PlainCredentials("mq_username", "mq_pwd")  # mq用户名和密码
    connection = pika.BlockingConnection(
    pika.ConnectionParameters(host="mq_host", port="mq_port,这里需是数字", virtual_host='/', credentials=credentials))
    channel = connection.channel()
    # 声明消息队列,消息将在这个队列传递,如不存在,则创建
    channel.queue_declare(queue='queuename', durable=False)
    record_dict = {}
    for i_dict in result_list:
        i_key, = i_dict
        i_value, = i_dict.values()
        record_dict[i_key] = i_value
    count = 1
    while count <= 5:
        now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        record_dict["now"] = now
        message = json.dumps(record_dict)
        # 向队列插入数值 routing_key是队列名
        channel.basic_publish(exchange='exchange_name', routing_key="queuename", body=message)
        print("发送数据:", now)
        # connection.close()
        time.sleep(2)
        count += 1

# 接收消息
def receive():
    credentials = pika.PlainCredentials("mq_username", "mq_pwd")  # mq用户名和密码
    connection = pika.BlockingConnection(
    pika.ConnectionParameters(host="mq_host", port="mq_port,这里需是数字", virtual_host='/', credentials=credentials))
    channel = connection.channel()
    # 声明消息队列,消息将在这个队列传递,如不存在,则创建
    channel.queue_declare(queue='queuename', durable=False)

    # 定义一个回调函数来处理消息队列中的消息,这里是打印出来
    def callback(ch, method, properties, body):
        ch.basic_ack(delivery_tag=method.delivery_tag)
        result = body.decode()
        result_dict = json.loads(result)
        print("-----接收数据:", result_dict["now"])
        # print(body.decode())

    # 告诉rabbitmq,用callback来接收消息
    channel.basic_consume('lyh-test', callback)
    # 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理
    channel.start_consuming()


import threading


t1 = threading.Thread(target=push)
t2 = threading.Thread(target=receive)
t1.start()
# t1.join() # 阻塞 等待t1线程执行完毕后可执行下面的代码
t2.start()
# 如果需要t1执行完毕才开始执行t2.可以在t2.start()之前join一下
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值