【问题标题】:How to add a header key:value pair when publishing a message with pika使用 pika 发布消息时如何添加标头键:值对
【发布时间】:2016-10-07 12:32:26
【问题描述】:

我正在编写一个自动化测试来测试消费者。到目前为止,我在发布消息时不需要包含标题,但现在我需要。而且它似乎缺少文档。

这是我的出版商:

class RMQProducer(object):

    def __init__(self, host, exchange, routing_key):
        self.host = host
        self.exchange = exchange
        self.routing_key = routing_key

    def publish_message(self, message):
        connection = pika.BlockingConnection(pika.ConnectionParameters(self.host))
        channel = connection.channel()
        message = json.dumps(message)
        channel.basic_publish(exchange=self.exchange,
                              routing_key=self.routing_key,
                              body=message)

我想做 smtn 之类的:

channel.basic_publish(exchange=self.exchange,
                      routing_key=self.routing_key,
                      body=message,
                      headers={"key": "value"})

在此邮件中添加标头的正确方法是什么?

【问题讨论】:

标签: python rabbitmq amqp pika


【解决方案1】:

官方文档中提到如下:

hdrs = {u'': u' ',
    u'': u'',
    u'': u''}
properties = pika.BasicProperties(app_id='example-publisher',
    content_type='application/json',  
    headers=hdrs)

【讨论】:

  • hdrs 字典有重复键 ;)
【解决方案2】:

您可以使用pika.BasicProperties 添加标题。

channel.basic_publish(exchange=self.exchange,
                      routing_key=self.routing_key,
                      properties=pika.BasicProperties(
                          headers={'key': 'value'} # Add a key/value header
                      ),
                      body=message)

pika 的官方文档确实没有完全涵盖这种情况,但文档确实列出了规范。如果您打算继续使用 pika,我强烈建议您为 this 页面添加书签。

【讨论】:

    【解决方案3】:

    不能说我从哪里得到这个,但我喜欢这样做:

    props = pika.BasicProperties({'headers': {'key': 'value'}})
    channel.basic_publish(exchange=self.exchange,
                              routing_key=self.routing_key,
                              body=message, properties = props)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 2020-12-26
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多