#!/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)