python使用rabbitmq实例六,远程结果返回(6)

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-1 04:18   130   0

前面的例子都有个共同点,就是发送端发送消息出去后没有结果返回。如果只是单纯发送消息,当然没有问题了,但是在实际中,常常会需要接收端将收到的消息进行处理之后,返回给发送端。

处理方法描述:发送端在发送信息前,产生一个接收消息的临时队列,该队列用来接收返回的结果。其实在这里接收端、发送端的概念已经比较模糊了,因为发送端也同样要接收消息,接收端同样也要发送消息,所以这里笔者使用另外的示例来演示这一过程。

示例内容:假设有一个控制中心和一个计算节点,控制中心会将一个自然数N发送给计算节点,计算节点将N值加1后,返回给控制中心。这里用center.py模拟控制中心,compute.py模拟计算节点。

compute.py代码分析

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 n + 1
17
18 #定义接收到消息的处理方法
19 def request(ch, method, properties, body):
20 print " [.] increase(%s)" % (body,)
21
22 response = increase(int(body))
23
24 #将计算结果发送回控制中心
25 ch.basic_publish(exchange='',
26 routing_key=properties.reply_to,
27 body=str(response))
28 ch.basic_ack(delivery_tag = method.delivery_tag)
29
30 channel.basic_qos(prefetch_count=1)
31 channel.basic_consume(request, queue='compute_queue')
32
33 channel.start_consuming()

计算节点的代码比较简单,值得一提的是,原来的接收方法都是直接将消息打印出来,这边进行了加一的计算,并将结果发送回控制中心。

center.py代码分析

1 #!/usr/bin/env python
2 #coding=utf8
3 import pika
4
5 class Center(object):
6 def __init__(self):
7 self.connection = pika.BlockingConnection(pika.ConnectionParameters(
8 host='localhost'))
9
10 self.channel = self.connection.channel()
11
12 #定义接收返回消息的队列
13 result = self.channel.queue_declare(exclusive=True)
14 self.callback_queue = result.method.queue
15
16 self.channel.basic_consume(self.on_response,
17 no_ack=True,
18 queue=self.callback_queue)
19
20 #定义接收到返回消息的处理方法
21 def on_response(self, ch, method, props, body):
22 self.response = body
23
24
25 def request(self, n):
26 self.response = None
27 #发送计算请求,并声明返回队列
28 self.channel.basic_publish(exchange='',
29 routing_key='compute_queue',
30 properties=pika.BasicProperties(
31 reply_to = self.callback_queue,
32 ),
33 body=str(n))
34 #接收返回的数据
35 while self.response is None:
36 self.connection.process_data_events()
37 return int(self.response)
38
39 center = Center()
40
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

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP