rabbitmq中使用多线程的python代码

服务端代码:

import functools
import threading
import traceback

import pika

class RabbitMQServer(object):
    def __init__(self, queue_name):
        self.queue_name = queue_name
        self.connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))

    def callback(self,ch, method, properties, body): #这个回调函数的参数固定是这样排序
        #在一个的channel中开始多个线程。因为rabbitmq中线程是不安全的,固需要使用add_callback_threadsafe()方法的线程。
        self.connection.add_callback_threadsafe(functools.partial(self.do_work, ch, method, properties, body))
        #不推荐使用以下线程的启动方式
        # thread = threading.Thread(target=self.do_work, args=(ch, method, properties, body))
        # thread.run()

    def do_work(self,channel, method, properties, body):
        try:
            print(f"Received message: {body}") #从客户端获取到的数据
            response = "Hello from server"
            channel.basic_publish(exchange='', routing_key=properties.reply_to,   #因为客户端生成的随机队列绑定到了默认的交换机,固exchange为空
                                  properties=pika.BasicProperties(correlation_id=properties.correlation_id), body=response)
            #手动应答,应答后该channel或被自动关闭。
            channel.basic_ack(delivery_tag=method.delivery_tag)
        except Exception as e:
            # 打印完整的异常信息
            traceback.print_exc()
            print("线程处理异常", e)

    def consum(self):
        while True: #可以确保某种原因导致进程终止后,可以继续启动一个新的进程
            try:
                channel = self.connection.channel()
                # 声明队列,没有就创建
                channel.queue_declare(queue=self.queue_name)
                # 声明交换机,和交换机跟队列进行绑定
                channel.exchange_declare(exchange="test", exchange_type='topic')
                channel.queue_bind(exchange="test", queue=self.queue_name, routing_key=self.queue_name)
                #一个channel中开启多个线程
                #消息队列中每来一条消息就调用一次回调函数callback,callback函数的参数固定为(ch, method, properties, body)
                channel.basic_consume(queue=self.queue_name, on_message_callback=self.callback, auto_ack=False) #自动应答设置auto_ack=True
                print(f"Server is listening for messages on queue: {self.queue_name}")
                channel.start_consuming()
            except Exception as e:
                traceback.print_exc()
                print("进程处理异常", e)
                channel.close()



if __name__ == "__main__":
    queue_name = "server_queue"
    server = RabbitMQServer(queue_name)
    server.consum()

客户端代码:

import pika
import uuid

class RabbitMQClient:
    def __init__(self, server_queue):
        self.connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
        self.channel = self.connection.channel()

        result = self.channel.queue_declare(queue='', exclusive=True) #随机生成队列
        self.callback_queue = result.method.queue #获取该随机生成的队列名称,该生成的队列没有绑定到指定的交换机,固绑定到了默认交换机
        #也可以根据实际需要绑定到对应的交换机中
        # self.channel.exchange_declare(exchange="test", exchange_type='topic')
        # self.channel.queue_bind(exchange="test", queue=self.callback_queue, routing_key=self.callback_queue)
        #订阅该队列,客户端获取响应数据,
        self.channel.basic_consume(queue=self.callback_queue, on_message_callback=self.on_response, auto_ack=True)

        self.server_queue = server_queue

    # 检查该响应消息的correlation_id属性是否与我们期待的一致,如果一致,将响应结果赋给self.response,然后跳出consuming循环
    def on_response(self, ch, method, props, body):
        if self.corr_id == props.correlation_id: #判断响应中的UUID是否一致。
            self.response = body

    def publish(self, message):
        channel = self.connection.channel()
        # 指定队列,没有就创建,
        channel.queue_declare(queue=self.server_queue)
        # 声明交换机,和交换机跟队列进行绑定
        channel.exchange_declare(exchange="test", exchange_type='topic')
        channel.queue_bind(exchange="test", queue=self.server_queue, routing_key=self.server_queue)

        channel.confirm_delivery() #确保可以送达
        self.response = None
        self.corr_id = str(uuid.uuid4())
        self.channel.basic_publish(
            exchange='test',
            routing_key=self.server_queue, #客户端的数据发送到该队列中
            properties=pika.BasicProperties( #在属性中包含服务端用于发送数据的队列名,和UUID唯一标识
                reply_to=self.callback_queue, # 将服务端执行结果返回到reply_to指定的队列中
                correlation_id=self.corr_id, # 通过该唯一id,可以区分哪个response对应该请求。
            ),
            body=message)
        # 注意,在这里不使用start_consuming去获取数据,因为这样会堵塞再这里,我们使用了另一种方法self.connection.process_data_events()
        while self.response is None:
            self.connection.process_data_events()
        return self.response

if __name__ == "__main__":
    server_queue = "server_queue"
    client = RabbitMQClient(server_queue)
    response = client.publish("Hello from client")
    print(f"Received response: {response.decode()}")

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

恋上钢琴的虫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值