python rabbitmq 线程池 客户端 服务端

服务端:

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):
        self.connection.add_callback_threadsafe(functools.partial(self.work, ch, method, properties, body))

    def work(self, channel,method, properties, body):
        try:
            print(f"received message {body}")
            response = "hello from server"
            channel.basic_publish(exchange='test', routing_key=properties.reply_to,
                                  properties=pika.BasicProperties(correlation_id=properties.correlation_id),body=response)

            channel.basic_ack(delivery_tag=method.delivery_tag)
        except Exception as e:
            traceback.print_exc()
            print("thread exeception",e)

    def consume(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.basic_consume(queue=self.queue_name, on_message_callback=self.callback,auto_ack=False)
                print(f"Server is listening for messages on queue:  {self.queue_name}")

                channel.start_consuming()

            except Exception as e:
                traceback.print_exc()
                print("thread processing exception")
                channel.close()


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

客户端:

import pika

import uuid

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

        self.server_queue = server_queue
        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)


    def on_response(self, ch, method,properpies,body):
        print("11111")
        if self.corrid == properpies.correlation_id:
            print("0000000")
            self.response = body
        print("22222")


    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.corrid = str(uuid.uuid4())
        self.channel.basic_publish(exchange='test', routing_key=self.server_queue,
                                   properties=pika.BasicProperties(
                                       reply_to=self.callback_queue,
                                       correlation_id=self.corrid
                                   ),body=message)
        while self.response is None:
            self.connection.process_data_events()
        return self.response

if __name__ == "__main__":
    server_queue = "server_queue"
    client = RabbitMQClient(server_queue)
    responsee = client.publish("hello from client")

    print(f"Received response: {responsee}")
使用Python可以通过pika库来连接和发送消息到RabbitMQ服务端,具体步骤如下: 1.安装pika库 可以使用pip进行安装,命令为: ``` pip install pika ``` 2.连接到RabbitMQ服务端 使用pika库中的BlockingConnection类可以连接到RabbitMQ服务端,代码示例: ``` import pika # 连接到RabbitMQ服务器 connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() ``` 其中,'localhost'是RabbitMQ服务器的地址,可以根据实际情况进行修改。 3.声明队列 在与RabbitMQ服务端建立连接后,需要声明一个队列,以便后续可以向该队列发送消息。代码示例: ``` # 声明队列 channel.queue_declare(queue='hello') ``` 其中,'hello'是队列的名称,可以根据实际情况进行修改。 4.发送消息 使用channel.basic_publish()函数可以向指定的队列发送消息,代码示例: ``` # 发送消息 channel.basic_publish(exchange='', routing_key='hello', body='Hello World!') print(" [x] Sent 'Hello World!'") ``` 其中,'hello'是队列的名称,'Hello World!'是要发送的消息内容。 完整代码示例: ``` import pika # 连接到RabbitMQ服务器 connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() # 声明队列 channel.queue_declare(queue='hello') # 发送消息 channel.basic_publish(exchange='', routing_key='hello', body='Hello World!') print(" [x] Sent 'Hello World!'") # 关闭连接 connection.close() ``` 以上就是使用Python通过RabbitMQ服务端通信的基本步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值