如何确保邮件传递?

ean*_*son 6 python message rabbitmq pika

您如何确保消息与Pika一起交付?默认情况下,如果邮件未成功传递,则不会向您提供错误.

在此示例中,在pika确认连接断开之前,可以发送几条消息.

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
for index in xrange(10):
    channel.basic_publish(exchange='', routing_key='hello', 
                          body='Hello World #%s!' % index)
    print('Total Messages Sent: %s' % x)
connection.close()
Run Code Online (Sandbox Code Playgroud)

ean*_*son 10

使用Pika时,channel.confirm_delivery()需要在开始发布消息之前设置标志.这很重要,以便Pika在发送下一条消息之前确认每条消息都已成功发送.然而,这将增加向RabbitMQ发送消息所花费的时间,因为在程序继续下一条消息之前需要确认传递.

channel.confirm_delivery()

try:
   for index in xrange(10):
       channel.basic_publish(exchange='', routing_key='hello', 
                              body='Hello World #%s!' % index)
       print('Total Messages Sent: %s' % x)
except pika.exceptions.ConnectionClosed as exc:
    print('Error. Connection closed, and the message was never delivered.')
Run Code Online (Sandbox Code Playgroud)

basic_publish将返回一个Boolean取决于邮件是否已发送.但是,如果在传输期间关闭连接并适当地处理它,则捕获潜在的异常非常重要.在这些情况下,异常将中断程序的流程.

  • @Jeffrey04:所有连接类型都应该支持它,因为它是在基本通道对象中定义的。https://github.com/pika/pika/blob/f8c263f234cca6b0f573ac63268a4034e32bd3eb/pika/channel.py#L388 (2认同)