How to add a header key:value pair when publishing a message with pika

岁酱吖の 提交于 2019-12-01 00:34:45

问题


I am writing an automated test to test a consumer. So far I did not need to include a header when publishing messages but now I do. And it seems like its lacking documentation.

This is my publisher:

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)

I want to do smtn like:

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

Whats the correct way to add headers to this message?


回答1:


You would use pika.BasicProperties to add headers.

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

The official documentation for pika does indeed not cover this scenario exactly, but the documentation does have the specifications listed. I would would strongly recommend that you bookmark this page, if you are going to continue using pika.




回答2:


cant say where i get this, but i do it like:

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



回答3:


The official document was mentioned as follows:

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


来源:https://stackoverflow.com/questions/37682184/how-to-add-a-header-keyvalue-pair-when-publishing-a-message-with-pika

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!