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
    评论
在CentOS操作系统上安装rabbitmq-c并使用,具体步骤如下: 1. 安装依赖项:在Linux终端中运行以下命令以安装rabbitmq-c的依赖项: ``` sudo yum install -y make cmake gcc gcc-c++ openssl-devel librabbitmq-devel ``` 2. 下载rabbitmq-c:从rabbitmq-c的官方网站(https://github.com/alanxz/rabbitmq-c)下载最新的源代码。 3. 构建rabbitmq-c:在rabbitmq-c的源代码目录中,运行以下命令以构建rabbitmq-c: ``` mkdir build && cd build cmake .. cmake --build . sudo cmake --build . --target install ``` 4. 在你的C代码中,使用以下头文件包含rabbitmq-c: ``` #include <rabbitmq-c/amqp.h> #include <rabbitmq-c/amqp_tcp_socket.h> ``` 5. 连接到RabbitMQ服务器:在你的C代码中,使用以下代码连接到RabbitMQ服务器: ``` amqp_socket_t *socket = amqp_tcp_socket_new(conn); if (!socket) { // 连接失败的处理 } int status = amqp_socket_open(socket, hostname, port); if (status != AMQP_STATUS_OK) { // 连接失败的处理 } amqp_connection_state_t conn = amqp_new_connection(); if (!conn) { // 连接失败的处理 } amqp_rpc_reply_t reply = amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN, username, password); if (reply.reply_type != AMQP_RESPONSE_NORMAL) { // 连接失败的处理 } ``` 6. 发送消息到队列:在你的C代码中,使用以下代码发送消息到队列: ``` amqp_basic_properties_t props; props._flags = AMQP_BASIC_CONTENT_TYPE_FLAG | AMQP_BASIC_DELIVERY_MODE_FLAG; props.content_type = amqp_cstring_bytes("text/plain"); props.delivery_mode = 2; // 持久化消息 amqp_bytes_t message_bytes = amqp_cstring_bytes("Hello, RabbitMQ!"); int status = amqp_basic_publish(conn, 1, amqp_cstring_bytes(exchange_name), amqp_cstring_bytes(routing_key), 0, 0, &props, message_bytes); if (status != AMQP_STATUS_OK) { // 发送失败的处理 } ``` 7. 接收消息:在你的C代码中,使用以下代码接收消息: ``` amqp_rpc_reply_t reply = amqp_basic_consume(conn, 1, amqp_cstring_bytes(queue_name), amqp_empty_bytes, 0, 1, 0, amqp_empty_table); if (reply.reply_type != AMQP_RESPONSE_NORMAL) { // 订阅失败的处理 } while (1) { amqp_envelope_t envelope; amqp_rpc_reply_t reply = amqp_consume_message(conn, &envelope, NULL, 0); if (reply.reply_type != AMQP_RESPONSE_NORMAL) { // 接收失败的处理 } // 在这里处理接收到的消息 amqp_destroy_envelope(&envelope); } ``` 以上就是在CentOS操作系统上安装rabbitmq-c并使用的步骤。希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值