RPC模式
发一条消息到远程机器去执行,然后吧执行结果返回,这种模式叫rpc(remote procedure call)
运用rpc之前要先了解RabbitMQ:python之RabbitMQ消息队列
然后我们用rpc模拟一个服务端和客户端,实现客户端传送数字,服务端运算斐波那契函数,然后返回值给客户端
具体看代码,里面有注释。
服务端
import pika
import time
#正常建立连接
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
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) #收到body
print("计算fib(%s)中..." % n)
response = fib(n) #处理得到结果
ch.basic_publish(exchange='',
routing_key=props.reply_to,
properties=pika.BasicProperties(correlation_id= \
props.correlation_id), #返回了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")
channel.start_consuming()
客户端
import pika
import uuid , time
class FibonacciRpcClient(object):
def __init__(self):
#初始化函数里正常连接pika
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
self.channel = self.connection.channel()
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: #收到了返回的随机字符串,当返回的id和本地的id是一样的,证明数据是对的
self.response = body
def call(self, n):
self.response = None
self.corr_id = str(uuid.uuid4()) #随机字符串id(有规则的字符串,用于往返验证是不是同机器发送的消息)
self.channel.basic_publish(exchange='',
routing_key='rpc_queue', #消息队列名称
properties=pika.BasicProperties(
reply_to=self.callback_queue, #让服务器端执行完后,吧结果返回到这个queue里
correlation_id=self.corr_id, #吧随机的id发给服务器端
),
body=str(n))
while self.response is None:
self.connection.process_data_events() #其实就是非阻塞版的start_consuming
time.sleep(0.5)
return int(self.response)
fibonacci_rpc = FibonacciRpcClient()
while True:
print("请输入要计算的fib n:")
n = input()
response = fibonacci_rpc.call(n)
print("结果为%r" % response)