ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
1. client ~~~ __author__ = 'dailin' import pika import uuid class FibonacciRpcClient(object): def __init__(self): credentials = pika.PlainCredentials('tuna', 'tuna') self.connection = pika.BlockingConnection(pika.ConnectionParameters( host='192.168.56.130', credentials=credentials )) self.channel = self.connection.channel() # 不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除 result = self.channel.queue_declare(exclusive=True) self.callback_queue = result.method.queue # 随机生成一个名字 self.channel.basic_consume(self.on_response, no_ack=True, # 声明消费 queue=self.callback_queue) def on_response(self, ch, method, props, body): if self.corr_id == props.correlation_id: self.response = body ''' 向server端发送命令,然后不断的调用消费server端返回的队列 ''' def call(self, n): self.response = None self.corr_id = str(uuid.uuid4()) # 生成任务的唯一标识,确保client与server之间任务的唯一性 self.channel.basic_publish(exchange='', routing_key='rpc_queue', properties=pika.BasicProperties( reply_to=self.callback_queue, # 回调队列 correlation_id=self.corr_id, ), body=str(n)) while self.response is None: self.connection.process_data_events() # 非阻塞调用consume,server端发来的消息 return int(self.response) fibonacci_rpc = FibonacciRpcClient() print(" [x] Requesting fib(30)") response = fibonacci_rpc.call(30) print(" [.] Got %r" % response) ~~~ 2. server ~~~ __author__ = 'dailin' import pika import time credentials = pika.PlainCredentials('tuna', 'tuna') connection = pika.BlockingConnection(pika.ConnectionParameters( host='192.168.56.130', credentials=credentials )) channel = connection.channel() channel.queue_declare(queue='rpc_queue') # 客户端队列 def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n - 1) + fib(n - 2) def on_request(ch, method, props, body): n = int(body) print(" [.] fib(%s)" % n) response = fib(n) # 给客户端返回结果 ch.basic_publish(exchange='', routing_key=props.reply_to, # 客户端发来的参数(指定server端回应消息的队列) properties=pika.BasicProperties(correlation_id= \ props.correlation_id), body=str(response)) ch.basic_ack(delivery_tag=method.delivery_tag) channel.basic_qos(prefetch_count=1) channel.basic_consume(on_request, queue='rpc_queue') print(" [x] Awaiting RPC requests") while True: print("waitting for commands.....") connection.process_data_events() # 和channel.start_consuming()作用一样都是消费,只不过是非阻塞 time.sleep(1) ~~~ connection.process_data_events() # 和channel.start_consuming()作用一样都是消费,只不过是非阻塞 channel.start_consuming():会一直阻塞的循环消费 connection.process_data_events() # 非阻塞消费,没有消息就过