Python RabbitMQ - 消费者只看到每一条消息

时间:2014-08-16 21:38:14

标签: python rabbitmq amqp pika

我正在使用Pika 0.98测试RabbitMQ的生产者消费者示例。我的生产者在我的本地PC上运行,消费者在亚马逊的EC2实例上运行。

我的制作人坐在循环中,每秒发送一些系统属性。问题是我只看到消费者阅读每一条第二条消息,就好像每条第二条消息都没有被阅读一样。例如,我的生产者打印出这个(时间戳,使用的cpu pct,使用的RAM):


    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 个答案:

答案 0 :(得分:6)

您的代码在逻辑上很好,并且在我的计算机上运行没有问题。您所看到的行为表明您可能意外地启动了两个消费者,每个消费者都从队列中获取消息,循环风格。尝试杀死额外的消费者(如果你能找到它),或者重新启动。