RabbitMQ---RPC

官方文档:https://www.rabbitmq.com/tutorials/tutorial-six-python.html

可运行位于远程计算机上的函数。

在这里插入图片描述

  • 当 client 启动,它会创建一个匿名的临时回调 queue
  • 对于一个 RPC 请求,client 发送的消息有两个属性:reply_to 设为回调 queue,correlation_id 对于每个 request 唯一。correlation_id 将 RPC 的 request 和 response 关联
  • request 被发送到一个 rpc 队列
  • server 在 rpc 队列上等待 request。当一个 request 到达,执行该 request 并通过 reply_to 属性中的回调 queue 向 client 发回结果
  • client 在回调 queue 等待数据。当消息到达,它会检查 correlation_id 属性,如果匹配则返回 response

rpc_server.py

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

# basic_consume 的回调函数
# 核心,执行 fib() 并返回 response
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(queue='rpc_queue', on_message_callback=on_request)

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

rpc_client.py

#!/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(queue='', exclusive=True)
        self.callback_queue = result.method.queue

        self.channel.basic_consume(
            queue=self.callback_queue,  # 向回调 queue 订阅消息,这样就能收到 RPC response
            on_message_callback=self.on_response,
            auto_ack=True)

	# 对于每个 response,该函数都会检查 correlation_id 是否匹配
	# 如果匹配,则将 response 保存在 self.response,并停止消费循环
    def on_response(self, ch, method, props, body):
        if self.corr_id == props.correlation_id:
            self.response = body

	# 发送 RPC 请求,阻塞直到收到消息
    def call(self, n):
        self.response = None
        
		#  首先创建一个唯一的 correlation_id
		# on_response 回调函数会将该值与 response 的属性匹配
        self.corr_id = str(uuid.uuid4()) 

		# 为了收到消息,client 需要发送一个回调 queue 的地址
		# 每个 request 都有一个唯一的 correlation_id
		# 每当从回调 queue 收到消息,都会查看 correlation_id,从而将 response 与 request 匹配
        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)

运行结果:

$ python3 rpc_server.py
 [x] Awaiting RPC requests
 [.] fib(30)
 $ python3 rpc_client.py 
 [x] Requesting fib(30)
 [.] Got 832040
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值