RabbitMQ学习笔记(五)

2017-03-09  本文已影响114人  嘿嘿_小于同学

远程调用(RPC)

ps: 使用pika
以前的笔记中,已经知道如何使用工作队列,在多个工作者Worker中分发耗时任务。
但是有时候我们可能遇到这样的情况,我们将一个函数运行在远程计算机上,然后另一个计算机等待从remote Computer上获取运行的结果,该怎么办?这种模式通常叫做远程过程调用(Remote Procedure Call)就是RPC。

客户端接口

为了展示PRC服务的使用,我们创建一个简单的客户顿类。它暴露出一个名为call()的方法用来发送一个RPC请求,并且在收到回应前保持阻塞。

fibonacci_rpc = FibonacciPrcClient()
result = fibonacci_rpc .call(4)
print " fib(4) is %r" % (result, )

回调队列

RabbbitMQ实现RPC是很容易的,一个客户端发送来请求信息,服务端将应用到一个回复信息中。为了接受到回复信息,客户端需要在发送请求的时候同时发送一个回调队列(callback queue)的地址。

result = channel.queue_declare(exclusive=True)
callback_queue = result.method.queue

channel.basic_publish(exchange='',
                      routing_key='rpc_queue',
                      properties=pika.BasicProperties(
                            reply_to = callback_queue,
                            ),
                      body=request)

消息属性

AMQP协议给消息定义了一系列的属性,常用的属性有:

关联标识

在每一个RPC请求都创建一个回调队列,这样如果请求数量多大导致系统内队列过多,造成性能下降,所以更好的方法就是为每一个客户端只创建一个独立回调队列。
但是有一个问题就是,一个客户端可能发送很多个请求,服务端处理完后怎么知道把相应发送给那个请求呢?correlation_id可以解决这个问题,相当于就是每一个请求会有有一个独一无二的值标识,当相应时,会匹配这个独一无二的值,将相应发送到指定的请求。

总结

如何工作

代码

rpc_server.py

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()

解释

rpc_client.py

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):
        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 = 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,)

解释

上一篇 下一篇

猜你喜欢

热点阅读