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一下

你可能感兴趣的:(经验篇,rabbitmq,python,分布式)