python使用rabbitmq实例七,相互关联编号correlation id(7)

本文介绍了一种使用correlationid在多计算节点环境下实现远程计算结果精确返回的方法,通过设置唯一标识码确保控制中心能够准确对应收到的消息与发送请求,即使消息不按顺序返回。

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

上一遍演示了远程结果返回的示例,但是有一个没有提到,就是correlation id,这个是个什么东东呢?

假设有多个计算节点,控制中心开启多个线程,往这些计算节点发送数字,要求计算结果并返回,但是控制中心只开启了一个队列,所有线程都是从这个队列里获取消息,每个线程如何确定收到的消息就是该线程对应的呢?这个就是correlation id的用处了。correlation翻译成中文就是相互关联,也表达了这个意思。

correlation id运行原理:控制中心发送计算请求时设置correlation id,而后计算节点将计算结果,连同接收到的correlation id一起返回,这样控制中心就能通过correlation id来标识请求。其实correlation id也可以理解为请求的唯一标识码。

示例内容:控制中心开启多个线程,每个线程都发起一次计算请求,通过correlation id,每个线程都能准确收到相应的计算结果。

compute.py代码分析

和上面一篇相比,只需修改一个地方:将计算结果发送回控制中心时,增加参数correlation_id的设定,该参数的值其实是从控制中心发送过来的,这里只是再次发送回去。代码如下:

1 #!/usr/bin/env python
2 #coding=utf8
3 import pika
4  
5 #连接rabbitmq服务器
6 connection = pika.BlockingConnection(pika.ConnectionParameters(
7         host='localhost'))
8 channel = connection.channel()
9  
10 #定义队列
11 channel.queue_declare(queue='compute_queue')
12 print ' [*] Waiting for n'
13  
14 #将n值加1
15 def increase(n):
16     return + 1
17  
18 #定义接收到消息的处理方法
19 def request(ch, method, props, body):
20     print " [.] increase(%s)"  % (body,)
21  
22     response = increase(int(body))
23  
24     #将计算结果发送回控制中心,增加correlation_id的设定
25     ch.basic_publish(exchange='',
26                      routing_key=props.reply_to,
27                      properties=pika.BasicProperties(correlation_id = \
28                                                      props.correlation_id),
29                      body=str(response))
30     ch.basic_ack(delivery_tag = method.delivery_tag)
31  
32 channel.basic_qos(prefetch_count=1)
33 channel.basic_consume(request, queue='compute_queue')
34  
35 channel.start_consuming()

center.py代码分析

控制中心代码稍微复杂些,其中比较关键的有三个地方:

  1. 使用python的uuid来产生唯一的correlation_id。
  2. 发送计算请求时,设定参数correlation_id。
  3. 定义一个字典来保存返回的数据,并且键值为相应线程产生的correlation_id。

代码如下:

1 #!/usr/bin/env python
2 #coding=utf8
3 import pika, threading, uuid
4  
5 #自定义线程类,继承threading.Thread
6 class MyThread(threading.Thread):
7     def __init__(self, func, num):
8         super(MyThread, self).__init__()
9         self.func = func
10         self.num = num
11  
12     def run(self):
13         print " [x] Requesting increase(%d)" % self.num
14         response = self.func(self.num)
15         print " [.] increase(%d)=%d" % (self.num, response)
16  
17 #控制中心类
18 class Center(object):
19     def __init__(self):
20         self.connection = pika.BlockingConnection(pika.ConnectionParameters(
21                 host='localhost'))
22  
23         self.channel = self.connection.channel()
24  
25         #定义接收返回消息的队列
26         result = self.channel.queue_declare(exclusive=True)
27         self.callback_queue = result.method.queue
28  
29         self.channel.basic_consume(self.on_response,
30                                    no_ack=True,
31                                    queue=self.callback_queue)
32  
33         #返回的结果都会存储在该字典里
34         self.response = {}
35  
36     #定义接收到返回消息的处理方法
37     def on_response(self, ch, method, props, body):
38         self.response[props.correlation_id] = body
39  
40     def request(self, n):
41         corr_id = str(uuid.uuid4())
42         self.response[corr_id] = None
43  
44         #发送计算请求,并设定返回队列和correlation_id
45         self.channel.basic_publish(exchange='',
46                                    routing_key='compute_queue',
47                                    properties=pika.BasicProperties(
48                                          reply_to = self.callback_queue,
49                                          correlation_id = corr_id,
50                                          ),
51                                    body=str(n))
52         #接收返回的数据
53         while self.response[corr_id] is None:
54             self.connection.process_data_events()
55         return int(self.response[corr_id])
56  
57 center = Center()
58 #发起5次计算请求
59 nums= [10203040 ,50]
60 threads = []
61 for num in nums:
62     threads.append(MyThread(center.request, num))
63 for thread in threads:
64     thread.start()
65 for thread in threads:
66     thread.join()

笔者开启了两个终端,来运行compute.py,开启一个终端来运行center.py,最后结果输出截图如下:

python使用rabbitmq多节点结果返回图示

python使用rabbitmq多节点结果返回图示

可以看到虽然获取的结果不是顺序输出,但是结果和源数据都是对应的。

这边示例的做法就是创建一个队列,使用correlation id来标识每次请求。也有做法可以不使用correlation id,就是每请求一次,就创建一个临时队列,不过这样太消耗性能了,官方也不推荐这么做。

### 使用 RabbitMQ 实现 RPC 的概述 RPC(远程过程调用)允许程序执行位于不同地址空间中的子程序,就像它是本地对象一样。通过 RabbitMQ 可以方便地实现在分布式环境下的远程方法调用功能。 #### 创建连接与通道 为了建立到 RabbitMQ 服务器的连接并获取通信信道,在 Python 中可以使用 `pika` 库来完成此操作: ```python import pika connection = pika.BlockingConnection( pika.ConnectionParameters(host='localhost')) channel = connection.channel() ``` 这段代码初始化了一个新的阻塞型连接实例,并指定了目标主机名为 'localhost';接着打开了一条用于发送消息的新频道[^3]。 #### 定义回调函数处理请求 当客户端发出请求时,服务端会监听特定队列上的消息,并由定义好的回调函数负责实际业务逻辑运算。对于本案例而言,则是计算给定数值对应的斐波那契数列项值: ```python def on_request(ch, method, props, body): n = int(body) print(f" [.] fib({n})") response = fibonacci(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) def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) ``` 这里实现了两个主要部分:一个是接收来自客户端的消息后触发执行的服务端处理器 `on_request()` 函数;另一个则是具体的算法实现——即求解第 N 个位置处的 Fibonacci 数字的方法 `fibonacci()`[^1]。 #### 设置队列参数和服务启动 为了让上述机制能够正常工作,还需要设置一些必要的配置选项,比如声明临时性的回复队列、指定消费模式等。最后一步就是让整个系统进入等待状态直到收到外部中断信号为止: ```python queue_name = "rpc_queue" result = channel.queue_declare(queue='', exclusive=True) callback_queue = result.method.queue channel.queue_declare(queue=queue_name) channel.basic_qos(prefetch_count=1) channel.basic_consume(queue=queue_name, on_message_callback=on_request) print(" [x] Awaiting RPC requests") channel.start_consuming() ``` 以上片段完成了如下几件事情: - 声明了一个独占性质的结果队列供后续作为响应路径; - 明确指出要监控哪个正式的工作队列 (`rpc_queue`) 来捕获新到达的任务指令; - 控制并发度为一次只处理一条未决事务; - 启动持续不断的循环读取流程以便及时响应任何可能到来的数据包[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值