Rabbitmq-rpc-python

Rabbitmq-rpc通信

1.概述

RPC(Remote Procedure Call:远程过程调用):一种进程间通信方式。允许像调用本地服务一样调用远程服务。

通信之间的交互有很多方式,mq就是其中的一种,本文以官网的demo做演示

image

上图是通过rabbitmq建立rpc通信的步骤(可以对应demo中的顺序):

# 1.server端声明队列"rpc_queue"
server.queue_declare("rpc_queue")

# 2.server端监听这个队列
server.basic_consume("rpc_queue")

# 3.client端声明回调的队列,这个队列默认可以不指定名称,默认名称类似于amq.gen.xxx
client.queue_declare(queue_name="amq.gen.xxx") # queue_name = amq.gen.xxx

# 4.client端监听这个匿名队列amq.gen.xxx
client.basic_consume(queue_name="amq.gen.xxx")

# 5.client端发送消息到"rpc_queue"这个队列并指定回调的队列是"amq.gen.xxx"
client.basic_publish(queue_name="rpc_queue",reply_to="amq.gen.xxx")

2.官网demo

  • Rpc-client
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import pika
import uuid


class FibonacciRpcClient(object):

    def __init__(self):
        # 建立连接
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(host='localhost'))

        # 建立通道
        self.channel = self.connection.channel()

        # 3.声明rpc-server ---> rpc-client 的 amq.gen
        result = self.channel.queue_declare(queue='', exclusive=True)  # amq.gen-5N69yyWCpKYpQ7qBsjB4Fw
        self.callback_queue = result.method.queue  # amq.gen-5N69yyWCpKYpQ7qBsjB4Fw

        # 4.客户端监听 amq.gen 这个队列中获取
        self.channel.basic_consume(
            queue=self.callback_queue,
            on_message_callback=self.on_response,
            auto_ack=True)

        self.response = None
        self.corr_id = None

    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())
        # 5.向 rpc_queue 队列推送消息
        self.channel.basic_publish(
            exchange='',
            routing_key='rpc_queue',
            properties=pika.BasicProperties(
                reply_to=self.callback_queue,  # amq.gen-5N69yyWCpKYpQ7qBsjB4Fw
                correlation_id=self.corr_id,
            ),
            body=str(n))
        self.connection.process_data_events(time_limit=None)
        return int(self.response)


fibonacci_rpc = FibonacciRpcClient()

print(" [x] Requesting fib(30)")
response = fibonacci_rpc.call(30)
print(" [.] Got %r" % response)
  • rpc-server
#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import pika
import json
# 建立连接
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost'))

# 建立通道
channel = connection.channel()

# 1.声明队列
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)


# callback 回调函数:作为server端收到消息就要根据参数执行
def on_request(ch, method, props, body):
    n = json.loads(body)

    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)
# 2.监听rpc_queue 毁掉函数on_request
channel.basic_consume(queue='rpc_queue', on_message_callback=on_request)

# 开始监听
print(" [x] Awaiting RPC requests")
channel.start_consuming()
posted @ 2022-09-09 16:57  GokuBlog  阅读(126)  评论(0编辑  收藏  举报