当前位置:Gxlcms > Python > Python操作RabbitMQ服务器消息队列的远程结果返回

Python操作RabbitMQ服务器消息队列的远程结果返回

时间:2021-07-01 10:21:17 帮助过:47人阅读

RabbitMQ是一款基于MQ的服务器,Python可以通过Pika库来进行程序操控,这里我们将来详解Python操作RabbitMQ服务器消息队列的远程结果返回:

先说一下笔者这里的测试环境:Ubuntu14.04 + Python 2.7.4
RabbitMQ服务器

  1. sudo apt-get install rabbitmq-server

Python使用RabbitMQ需要Pika库

  1. sudo pip install pika

远程结果返回
消息发送端发送消息出去后没有结果返回。如果只是单纯发送消息,当然没有问题了,但是在实际中,常常会需要接收端将收到的消息进行处理之后,返回给发送端。

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

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

compute.py代码分析

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

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

center.py代码分析

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

相互关联编号correlation id
上一遍演示了远程结果返回的示例,但是有一个没有提到,就是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. #连接rabbitmq服务器
  5. connection = pika.BlockingConnection(pika.ConnectionParameters(
  6. host='localhost'))
  7. channel = connection.channel()
  8. #定义队列
  9. channel.queue_declare(queue='compute_queue')
  10. print ' [*] Waiting for n'
  11. #将n值加1
  12. def increase(n):
  13. return n + 1
  14. #定义接收到消息的处理方法
  15. def request(ch, method, props, body):
  16. print " [.] increase(%s)" % (body,)
  17. response = increase(int(body))
  18. #将计算结果发送回控制中心,增加correlation_id的设定
  19. ch.basic_publish(exchange='',
  20. routing_key=props.reply_to,
  21. properties=pika.BasicProperties(correlation_id = \
  22. props.correlation_id),
  23. body=str(response))
  24. ch.basic_ack(delivery_tag = method.delivery_tag)
  25. channel.basic_qos(prefetch_count=1)
  26. channel.basic_consume(request, queue='compute_queue')
  27. channel.start_consuming()

center.py代码分析

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

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

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

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

Python操作RabbitMQ服务器消息队列的远程结果返回

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

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

更多Python操作RabbitMQ服务器消息队列的远程结果返回相关文章请关注PHP中文网!

人气教程排行