0
votes

Consumer.py:

#!/usr/bin/env python import pika, sys, os def main(): connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel()

channel.exchange_declare(exchange='headers_logs', exchange_type='headers')

channel.queue_declare(queue='', exclusive=True)
queue_name = "HeadersQueue1"

channel.queue_bind(exchange='headers_logs', queue=queue_name)

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

print(' [*] Waiting for logs. To exit press CTRL+C')
channel.basic_consume(
    queue=queue_name, on_message_callback=callback, auto_ack=True)

channel.start_consuming()

if name == 'main': try: main() except KeyboardInterrupt: print('Interrupted') try: sys.exit(0) except SystemExit: os._exit(0)

Publish.py:

#!/usr/bin/env python import pika import sys connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) channel = connection.channel()

channel.exchange_declare(exchange='headers_logs',exchange_type='headers')

message = ' '.join(sys.argv[1:]) or "Hello World!"

channel.basic_publish(exchange='headers_logs',headers={"name":"ram"},body=message) print(" [x] Sent %r" % message) connection.close()

Here I have written consumer and publish program like above. Can anyone please guide that how to write Simple headersExchange program in rabbitMq using python

1

1 Answers

0
votes

To use a headers exchange, you need to declare the exchange type as headers, not fanout as in your question's text.

exchangeName = 'headers_logs'
channel.exchange_declare(exchangeName, exchange_type='headers', durable=True)

Then create the queue and bind it to the exchange using the headers. Note that 'x-match' here can be set to match any or all headers. The routing key is set to empty string because it will not be used for routing messages.

qName = 'queue_logs'
channel.queue_declare(queue=qNameI, durable=True)
channel.queue_bind(qName, exchangeName, routing_key='',  arguments={'x-match': 'any', 'key1': 'one', 'key2': 'two'})

Now we can publish a message to the exchange with a set of headers:

channel.basic_publish(
    exchange=exchangeName, 
    routing_key='', 
    body='test message body',
    properties=pika.BasicProperties(
        delivery_mode = 2, # make message persistent
        headers = {'key1':'one', 'key2': 'three'}
    )
)

I have only matched 'key1' in this message to demonstrate that 'x-match' has been set to 'any'.