RPC的全称是Remote procedure call,就是远程过程调用,在远端(服务器端)调用过程(函数),服务器回传结果,本地再收到结果。
Rabbitmq主要为RPC提供传输请求和结果的途径,如下图。
客户端发起请求是指定另外两个属性,reply-to属性表示将通过哪个管道收取请求的结果,correlation-id是每个请求都不同的唯一id,服务端的结果中,会附带该id;客户端收到结果后,会检查结果附带的id是否和请求中的id相同,如果不同则丢弃该结果。
注意上图中的rpc_queue和reply_to指定的queue,前者是读取请求的队列,后者是读取结果的队列。
下面是python实现RPC的代码,理解上面的请求响应结构后,下面的代码不难读懂
客户端
#!/usr/bin/env python import pika import uuid class FibonacciRpcClient(object): def __init__(self): 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): # 收到远程调用的结果之后,要检查结果的correlation id是否和发出请求时一致 if self.corr_id == props.correlation_id: self.response = body def call(self, n): self.response = None self.corr_id = str(uuid.uuid4()) self.channel.basic_publish(exchange='', routing_key='rpc_queue', properties=pika.BasicProperties( # 在发出请求时,指定reply_to和correlation id两个属性 reply_to = self.callback_queue, correlation_id = self.corr_id, ), body=str(n)) while self.response is None: self.connection.process_data_events() return int(self.response) fibonacci_rpc = FibonacciRpcClient() print(" [x] Requesting fib(30)") response = fibonacci_rpc.call(30) print(" [.] Got %r" % response)
服务端
#!/usr/bin/env python import pika 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) print(" [.] fib(%s)" % n) response = fib(n) ch.basic_publish(exchange='', routing_key=props.reply_to, 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") channel.start_consuming()