RabbitMQ 消息队列 实现RPC 远程过程调用交互
#!/usr/bin/env python # Author:Zhangmingda import pika,time import uuid class FibonacciRpcClient(object): def __init__(self): ''''定义socket''' self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) '''创建管道''' self.channel = self.connection.channel() '''''' result = self.channel.queue_declare(exclusive=True) #获取消息队列实例。不指定queue名字,rabbit会随机分配一个名字,exclusive=True指的是使用此queue的消费者断开后,自动删除这个queue self.callback_queue = result.method.queue #从消息队列实例取得消息队列名字 self.channel.basic_consume(self.on_response, no_ack=True, #定义回调函数 queue=self.callback_queue) #回调消息发给哪个queue def on_response(self, ch, method, props, body): if self.corr_id == props.correlation_id: self.response = body def call(self, n): #发布消息到Rabbitmq self.response = None self.corr_id = str(uuid.uuid4()) #判断是否为我自己发出的消息的回应,提前给消息加上uuid给server self.channel.basic_publish(exchange='', #发消息到Rabbitmq routing_key='rpc_queue', #向rpc_queue发送消息 properties=pika.BasicProperties( reply_to=self.callback_queue, #告诉服务端,回应消息走哪个queue correlation_id=self.corr_id, #uuid参数 ), body=str(n)) #发送的消息内容 while self.response is None:#如果为空说明消息发出后没有收到回应。所以回调函数还未执行 print('no message ...') time.sleep(0.05) self.connection.process_data_events() #非阻塞版start_consuming()的开始接收服务端反馈 return int(self.response) #接收到了就反馈 fibonacci_rpc = FibonacciRpcClient() #创建实例 fib_set = 10 print(" [x] Requesting fib 【第%s个斐波那契数字为】"%fib_set) response = fibonacci_rpc.call(fib_set) print(" [.] 计算结果 Got %r" % response)
#!/usr/bin/env python # Author:Zhangmingda import pika import time connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) #建立socket实例 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) #取到传过来的bytes类型的str转换为int print(" [.] fib(%s)" % n) response = fib(n) #调用函数计算应得数值 ch.basic_publish(exchange='', #向客户指定的消息队列回发计算结果 routing_key=props.reply_to, #获取客户端指定的回发状态的queuename,作为routing_key properties=pika.BasicProperties(correlation_id= props.correlation_id),#获取客户的校验值回传 body=str(response))#将计算结果转为str回传 ch.basic_ack(delivery_tag=method.delivery_tag) #告诉rebbitmq,处理完成消息可以自动删除 channel.basic_qos(prefetch_count=1)#控制排队个数 channel.basic_consume(on_request, queue='rpc_queue') #指定接收消息的队列,和处理消息的回调函数 print(" [x] Awaiting RPC requests") channel.start_consuming() #开始接收消息
posted on 2018-08-14 14:32 zhangmingda 阅读(300) 评论(0) 编辑 收藏 举报