前面的例子都有个共同点,就是发送端发送消息出去后没有结果返回。如果只是单纯发送消息,当然没有问题了,但是在实际中,常常会需要接收端将收到的消息进行处理之后,返回给发送端。
处理方法描述:发送端在发送信息前,产生一个接收消息的临时队列,该队列用来接收返回的结果。其实在这里接收端、发送端的概念已经比较模糊了,因为发送端也同样要接收消息,接收端同样也要发送消息,所以这里笔者使用另外的示例来演示这一过程。
示例内容:假设有一个控制中心和一个计算节点,控制中心会将一个自然数N发送给计算节点,计算节点将N值加1后,返回给控制中心。这里用center.py模拟控制中心,compute.py模拟计算节点。
compute.py代码分析
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, properties, body): |
20 | print " [.] increase(%s)" % (body,) |
22 | response = increase( int (body)) |
25 | ch.basic_publish(exchange = '', |
26 | routing_key = properties.reply_to, |
28 | ch.basic_ack(delivery_tag = method.delivery_tag) |
30 | channel.basic_qos(prefetch_count = 1 ) |
31 | channel.basic_consume(request, queue = 'compute_queue' ) |
33 | channel.start_consuming() |
计算节点的代码比较简单,值得一提的是,原来的接收方法都是直接将消息打印出来,这边进行了加一的计算,并将结果发送回控制中心。
center.py代码分析
7 | self .connection = pika.BlockingConnection(pika.ConnectionParameters( |
10 | self .channel = self .connection.channel() |
13 | result = self .channel.queue_declare(exclusive = True ) |
14 | self .callback_queue = result.method.queue |
16 | self .channel.basic_consume( self .on_response, |
18 | queue = self .callback_queue) |
21 | def on_response( self , ch, method, props, body): |
28 | self .channel.basic_publish(exchange = '', |
29 | routing_key = 'compute_queue' , |
30 | properties = pika.BasicProperties( |
31 | reply_to = self .callback_queue, |
35 | while self .response is None : |
36 | self .connection.process_data_events() |
37 | return int ( self .response) |
41 | print " [x] Requesting increase(30)" |
42 | response = center.request( 30 ) |
43 | print " [.] Got %r" % (response,) |
上例代码定义了接收返回数据的队列和处理方法,并且在发送请求的时候将该队列赋值给reply_to,在计算节点代码中就是通过这个参数来获取返回队列的。
打开两个终端,一个运行代码python compute.py,另外一个终端运行center.py,如果执行成功,应该就能看到效果了。
笔者在测试的时候,出了些小问题,就是在center.py发送消息时没有指明返回队列,结果compute.py那边在计算完结果要发回数据时报错,提示routing_key不存在,再次运行也报错。用rabbitmqctl list_queues查看队列,发现compute_queue队列有1条数据,每次重新运行compute.py的时候,都会重新处理这条数据。后来使用/etc/init.d/rabbitmq-server restart重新启动下rabbitmq就ok了。
参考文章:http://www.rabbitmq.com/tutorials/tutorial-six-python.html