我想根据消息头路由rabbitmq消息,我已经创建了一个适当的基础设施,包括消息头交换、队列、绑定等。
import pika
# define variables
url = "amqp://rabbitmq-host/"
exchange = 'headers-exchange',
s_queue = 'StudentQueue'
t_queue = 'TeacherQueue'
# create connection
connection_parameters = pika.URLParameters(url)
connection = pika.BlockingConnection(connection_parameters)
channel = connection.channel()
# declare exchange
channel.exchange_declare(
exchange=exchange,
exchange_type='headers',
durable=True
)
# declare student queue
channel.queue_declare(
queue=s_queue,
durable=True,
)
# bind student queue
channel.queue_bind(
exchange=exchange,
queue=s_queue,
# bind arguments:
# match all the given headers
# match x-queue should be equal to student
arguments={
"x-match": "all",
"x-queue": "student"
},
)
# declare teacher queue
channel.queue_declare(
queue=t_queue,
durable=True,
)
# bind teacher queue
channel.queue_bind(
exchange=exchange,
queue=t_queue,
# bind arguments:
# match all the given headers
# match x-queue should be equal to teacher
arguments={
"x-match": "all",
"x-queue": "teacher"
},
)
发布模块(publish.py
)如下所示:
import datetime
import time
import uuid
import pika
# define variables
url = "amqp://rabbitmq-host/"
exchange = 'headers-exchange',
# create connection
connection_parameters = pika.URLParameters(url)
connection = pika.BlockingConnection(connection_parameters)
channel = connection.channel()
# declare exchange
channel.exchange_declare(
exchange=exchange,
exchange_type='headers',
durable=True
)
# define message id
id_ = uuid.uuid4()
message_id = id_.hex
timestamp = time.mktime(datetime.datetime.now().timetuple())
# define message property esp. headers
properties = pika.BasicProperties(
content_type="application/json",
# match x-queue = student header
# to the StudentQueue
headers={"x-queue": "student"}
message_id=message_id,
timestamp=timestamp,
delivery_mode=2,
)
# publish the message for student queue
channel.basic_publish(
exchange=exchange,
routing_key="",
body="for student queue only",
properties=properties,
)
发布的消息只应传递到StudentQueue
,因为我们有headers={"x-queue": "student"}
,但它也传递到TeacherQueue
,这是不正确的。
应用程序版本列表为:
RabbitMQ: 3.6.16
Erlang: 20.3.4
Pika: 1.2.1
有没有人能指出我错过的明显之处,有没有可能与不匹配的版本有关?任何帮助都将不胜感激。
干杯DD
1条答案
按热度按时间v7pvogib1#
来自文档:
对于"any"和"all",以字符串x-开头的标头将不用于评估匹配项。
因此,在您的示例中,绑定参数和消息头都将
"x-queue": "teacher"
更改为"queue": "teacher"
(但仍保留绑定参数"x-match": "all"
不变)。