接收器部分缺少rabbitmq消息

时间:2016-05-02 11:08:04

标签: python rabbitmq pika

我已经在我的服务器中实现了RabbitMQ。所以基本上它的作用是主服务器将消息传递给工作服务器。 我面临的问题是服务器没有收到我传递的所有消息。 即如果我发送10条消息,则只收到4条消息。

知道我哪里错了。

接收代码

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='hello')

def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

channel.basic_consume(callback,
                      queue='hello',
                      no_ack=True)

print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

发布代码

import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='task_queue', durable=True)

message = ' '.join(sys.argv[1:]) or "Hello World!"
channel.basic_publish(exchange='',
                      routing_key='task_queue',
                      body=message,
                      properties=pika.BasicProperties(
                         delivery_mode = 2, # make message persistent
                      ))
print(" [x] Sent %r" % message)
connection.close()

1 个答案:

答案 0 :(得分:0)

假设您要发布到同一个队列(否则您发布的示例会显示)。我建议你启用confirm delivery标志。这将确保您的消息被传递,如果不是,它将抛出异常,或者发布将返回False。

channel = connection.channel()
channel.confirm_delivery()
published = channel.basic_publish(...)
if not published:
    raise Exception("Unable to publish message!")

在开始使用消息之前,为RabbitMQ安装management plugin并检查队列也是值得的。通过这种方式,您可以验证消息是否已发布,以后消耗。

相关问题