RabbitMQ(part6请求/回复模式示例)----Remote procedure call (RPC)

本文介绍如何利用RabbitMQ构建远程过程调用(RPC)系统。通过客户端和服务端的交互,演示了如何发送请求及接收响应的过程。具体包括设置RabbitMQ连接、声明队列、定义回调函数等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需要将一个函数运行在远程计算机上并且等待从那儿获取结果时,该怎么办呢?这种模式通常被称为远程程序调用(Remote Procedure Call)或者RPC。

使用RabbitMQ来构建一个RPC系统:包含一个客户端和一个RPC服务器。

一、远程过程调用:


Putting it all together

The code for rpc_server.py:

#-*- coding:utf-8 –*-
#!/usr/bin/env python
import pika

#像往常一样,我们建立连接,声明队列
connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))

channel = connection.channel()

channel.queue_declare(queue='rpc_queue')

#声明我们的fibonacci函数,它假设只有合法的正整数当作输入。
def fib(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

#为 basic_consume 声明了一个回调函数,这是RPC服务器端的核心。它执行实际的操作并且作出响应。
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)

#或许我们希望能在服务器上多开几个线程。
#为了能将负载平均地分摊到多个服务器,我们需要将 prefetch_count 设置好
channel.basic_qos(prefetch_count=1)

channel.basic_consume(on_request, queue='rpc_queue')

print " [x] Awaiting RPC requests"
channel.start_consuming()

The server code is rather straightforward:


#-*- coding:utf-8 –*-
#!/usr/bin/env python
import pika
import uuid

class FibonacciRpcClient(object):
    def __init__(self):
#建立连接、通道并且为回复(replies)声明独享的回调队列
        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) #订阅这个回调队列,以便接收RPC的响应

# on_response回调函数对每一个响应执行一个非常简单的操作,检查每一个响应消息的correlation_id属性是否与我们期待的一致,如果一致,将响应结果赋给self.response,然后跳出consuming循环
    def on_response(self, ch, method, props, body):
        if self.corr_id == props.correlation_id:
            self.response = body

#接下来,我们定义我们的主要方法 call 方法。它执行真正的RPC请求。
#在这个方法中,首先我们生成一个唯一的 correlation_id,值并且保存起来,'on_response'回调函数会用它来获取符合要求的响应。
#接下来,我们将带有 reply_to 和 correlation_id 属性的消息发布出去
    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,)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值