我在python中为rabbit mq编写了以下工作生成器使用者代码。 但我有一个扭曲。消费者在0.5秒内不断将数据放入队列中,但现在我希望我的消费者每3秒唤醒一次并获取发布者已放入队列的所有6个数据并再次休眠3秒。我想为此进入无限循环。
但我不确定如何在兔子mq中实现这一目标
import pika
import time
import datetime
connection = pika.BlockingConnection(pika.ConnectionParameters(
'localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
value=str(int(time.time()))
for i in range (1000):
channel.basic_publish(exchange='',routing_key='hello',body='{"action": "print", "method": "onData", "data": "Madan Mohan"}')
time.sleep(0.5)
connection.close()
#!/usr/bin/env python
import pika
import time
import json
import datetime
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
#print " current time: %s " % (str(int((time.time())*1000)))
d=json.loads(body)
print d
channel.basic_consume(callback,
queue='hello',
no_ack=True)
channel.start_consuming()
答案 0 :(得分:2)
第一个在回调中使用sleep的解决方案。但可能它不是一个好的解决方案,因为basic_consume旨在尽可能快地(异步)获取消息。
got = 0
def callback(ch, method, properties, body):
#print " current time: %s " % (str(int((time.time())*1000)))
d=json.loads(body)
print d
got = got + 1
if got == 6
got = 0
time.sleep(3)
使用channel.basic_get。这是一种更适合同步获取消息的解决方案。
got = 0
while True
channel.basic_get(callback,
queue='hello',
no_ack=True)
got = got + 1
if got == 6
got = 0
time.sleep(3)