RabbitMQ

Headers exchange

介绍:
  headers exchange与 direct、topic、fanout不同,它是通过匹配 AMQP 协议消息的 header 而非路由键,有点像HTTP的Headers;
headers exchange与 direct Exchange类似,性能方面比后者查很多,所以在实际项目中用的很少。   

  在绑定Queue与Exchange时指定一组header键值对;当消息发送到Exchange时,RabbitMQ会取到该消息的headers(也是一个键值对的形式),
对比其中的键值对是否完全匹配Queue与Exchange绑定时指定的键值对。如果完全匹配则消息会路由到该Queue,否则不会路由到该Queue。

  headers属性是一个键值对,键值对的值可以是任何类型。而fanout,direct,topic 的路由键都需要要字符串形式的。
键值对要求携带一个键“x-match”,这个键的Value可以是any或者all,这代表消息携带的header是需要全部匹配(all),还是仅匹配一个键(any)就可以了。

Putting it all together

send.py

import pika

CREDENTIALS = pika.PlainCredentials('mq_user', 'password')
PARAMETERS = pika.ConnectionParameters('10.6.3.12', 5677,
                                       'smes', CREDENTIALS)
connection = pika.BlockingConnection(PARAMETERS)
channel = connection.channel()
channel.exchange_declare(exchange='my-headers-exchange', exchange_type='headers')
channel.basic_publish(
    exchange='my-headers-exchange',
    routing_key='',
    body='Hello World!',
    properties=pika.BasicProperties(headers={'h1': 'Header1'}))

receive.py

import pika

CREDENTIALS = pika.PlainCredentials('mq_user', 'password')
PARAMETERS = pika.ConnectionParameters('10.6.3.12', 5677,
                                       'smes', CREDENTIALS)
connection = pika.BlockingConnection(PARAMETERS)

channel = connection.channel()
channel.exchange_declare(exchange='my-headers-exchange', exchange_type='headers')
channel.queue_declare(queue='HealthQ')
channel.queue_bind(
    queue='HealthQ',
    exchange='my-headers-exchange',
    routing_key='',
    arguments={'x-match': 'any', 'h1': 'Header1', 'h2': 'Header2'})


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


channel.basic_consume(queue='HealthQ', on_message_callback=callback, auto_ack=True)
channel.start_consuming()

  

原文地址:https://www.cnblogs.com/liuwei0824/p/14714825.html