Python RabbitMQ - 消费者只看到每第二条消息
我正在用Pika 0.98测试一个RabbitMQ的生产者-消费者示例。我的生产者在本地电脑上运行,而消费者则在亚马逊的EC2实例上。
我的生产者在一个循环中,每秒发送一些系统属性。问题是,我发现消费者只读取每第二条消息,感觉好像每第二条消息都没有被读取。例如,我的生产者打印出的内容是这样的(时间戳、CPU使用百分比、内存使用量):
2014-08-16 14:36:17.576000 -0700,16.0,8050806784 2014-08-16 14:36:18.578000 -0700,15.5,8064458752 2014-08-16 14:36:19.579000 -0700,15.0,8075313152 2014-08-16 14:36:20.580000 -0700,12.1,8074121216 2014-08-16 14:36:21.581000 -0700,16.0,8077778944 2014-08-16 14:36:22.582000 -0700,14.2,8075038720
但是我的消费者打印出的内容却是这样的:
Received '2014-08-16 14:36:17.576000 -0700,16.0,8050806784' Received '2014-08-16 14:36:19.579000 -0700,15.0,8075313152' Received '2014-08-16 14:36:21.581000 -0700,16.0,8077778944'
生产者的代码是:
import pika
import psutil
import time
import datetime
from dateutil.tz import tzlocal
import logging
logging.getLogger('pika').setLevel(logging.DEBUG)
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='54.191.161.213'))
channel = connection.channel()
channel.queue_declare(queue='ems.data')
while True:
now = datetime.datetime.now(tzlocal())
timestamp = now.strftime('%Y-%m-%d %H:%M:%S.%f %z')
msg="%s,%.1f,%d" % (timestamp, psutil.cpu_percent(),psutil.virtual_memory().used)
channel.basic_publish(exchange='',
routing_key='ems.data',
body=msg)
print msg
time.sleep(1)
connection.close()
消费者的代码是:
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='0.0.0.0'))
channel = connection.channel()
channel.queue_declare(queue='hello')
print ' [*] Waiting for messages. To exit press CTRL+C'
def callback(ch, method, properties, body):
print " [x] Received %r" % (body,)
channel.basic_consume(callback,
queue='hello',
no_ack=True)
channel.start_consuming()
1 个回答
10
你的代码逻辑上没问题,在我的电脑上也能正常运行。你遇到的这个情况可能是因为你不小心启动了两个消费者,每个消费者都在轮流从队列中取消息。你可以试着结束那个多余的消费者(如果你能找到的话),或者重启一下电脑。