上一遍演示了远程结果返回的示例,但是有一个没有提到,就是correlation id,这个是个什么东东呢?
假设有多个计算节点,控制中心开启多个线程,往这些计算节点发送数字,要求计算结果并返回,但是控制中心只开启了一个队列,所有线程都是从这个队列里获取消息,每个线程如何确定收到的消息就是该线程对应的呢?这个就是correlation id的用处了。correlation翻译成中文就是相互关联,也表达了这个意思。
correlation id运行原理:控制中心发送计算请求时设置correlation id,而后计算节点将计算结果,连同接收到的correlation id一起返回,这样控制中心就能通过correlation id来标识请求。其实correlation id也可以理解为请求的唯一标识码。
示例内容:控制中心开启多个线程,每个线程都发起一次计算请求,通过correlation id,每个线程都能准确收到相应的计算结果。
compute.py代码分析
和上面一篇相比,只需修改一个地方:将计算结果发送回控制中心时,增加参数correlation_id的设定,该参数的值其实是从控制中心发送过来的,这里只是再次发送回去。代码如下:
6 | connection = pika.BlockingConnection(pika.ConnectionParameters( |
8 | channel = connection.channel() |
11 | channel.queue_declare(queue = 'compute_queue' ) |
12 | print ' [*] Waiting for n' |
19 | def request(ch, method, props, body): |
20 | print " [.] increase(%s)" % (body,) |
22 | response = increase( int (body)) |
25 | ch.basic_publish(exchange = '', |
26 | routing_key = props.reply_to, |
27 | properties = pika.BasicProperties(correlation_id = \ |
28 | props.correlation_id), |
30 | ch.basic_ack(delivery_tag = method.delivery_tag) |
32 | channel.basic_qos(prefetch_count = 1 ) |
33 | channel.basic_consume(request, queue = 'compute_queue' ) |
35 | channel.start_consuming() |
center.py代码分析
控制中心代码稍微复杂些,其中比较关键的有三个地方:
- 使用python的uuid来产生唯一的correlation_id。
- 发送计算请求时,设定参数correlation_id。
- 定义一个字典来保存返回的数据,并且键值为相应线程产生的correlation_id。
代码如下:
3 | import pika, threading, uuid |
6 | class MyThread(threading.Thread): |
7 | def __init__( self , func, num): |
8 | super (MyThread, self ).__init__() |
13 | print " [x] Requesting increase(%d)" % self .num |
14 | response = self .func( self .num) |
15 | print " [.] increase(%d)=%d" % ( self .num, response) |
20 | self .connection = pika.BlockingConnection(pika.ConnectionParameters( |
23 | self .channel = self .connection.channel() |
26 | result = self .channel.queue_declare(exclusive = True ) |
27 | self .callback_queue = result.method.queue |
29 | self .channel.basic_consume( self .on_response, |
31 | queue = self .callback_queue) |
37 | def on_response( self , ch, method, props, body): |
38 | self .response[props.correlation_id] = body |
41 | corr_id = str (uuid.uuid4()) |
42 | self .response[corr_id] = None |
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, |
53 | while self .response[corr_id] is None : |
54 | self .connection.process_data_events() |
55 | return int ( self .response[corr_id]) |
59 | nums = [ 10 , 20 , 30 , 40 , 50 ] |
62 | threads.append(MyThread(center.request, num)) |
63 | for thread in threads: |
65 | for thread in threads: |
笔者开启了两个终端,来运行compute.py,开启一个终端来运行center.py,最后结果输出截图如下:
python使用rabbitmq多节点结果返回图示
可以看到虽然获取的结果不是顺序输出,但是结果和源数据都是对应的。
这边示例的做法就是创建一个队列,使用correlation id来标识每次请求。也有做法可以不使用correlation id,就是每请求一次,就创建一个临时队列,不过这样太消耗性能了,官方也不推荐这么做。