如何从回调中访问信息
How to access information from callback
我只想知道如何从回调中获取数据。
import pika
def callback(channel, method, properties, body):
print(method.get_body())
print(method.get_properties())
channel.basic_ack(delivery_tag=method.delivery_tag)
def on_open(connection):
connection.channel(on_open_callback=on_channel_open)
def on_channel_open(channel):
channel.basic_consume(on_message_callback = callback, queue='q1')
channel.basic_consume(on_message_callback = callback, queue='q2')
credentials = pika.PlainCredentials('user', 'password', erase_on_connect=False)
params = pika.ConnectionParameters("localhost", 5672, '/', credentials)
connection = pika.SelectConnection(parameters=params,
on_open_callback=on_open)
try:
connection.ioloop.start()
except KeyboardInterrupt:
connection.close()
connection.ioloop.start()
回调中两条打印行的输出是:
<class 'pika.spec.Basic.Deliver'>
<Basic.Deliver(['consumer_tag=ctag1.2607da3f5f9f4e5592991a16cc0aca6e', 'delivery_tag=1', 'exchange=gatekeeper', 'redelivered=True', 'routing_key=laa'])>
如何提取 'routing_key'?查看源代码后,我相信 method.get_properties()
会起作用,但事实并非如此。
虽然记录不完整,但 callback
函数将使用 4 个参数调用:
- 您使用的频道
- 一个
Method
实例(在本例中是一个Deliver
实例)
- 一个
BasicProperties
实例
- 一具尸体(
bytes
)
Deliver
实例将有一个名为 routing_key
的属性。所以你的函数看起来像这样:
def callback(channel, method, properties, body):
print(method.get_body())
print(method.get_properties())
print(method.routing_key)
channel.basic_ack(delivery_tag=method.delivery_tag)
PS。将调用回调的参数与 here 中描述的相同,其中 是 实际记录的。
我只想知道如何从回调中获取数据。
import pika
def callback(channel, method, properties, body):
print(method.get_body())
print(method.get_properties())
channel.basic_ack(delivery_tag=method.delivery_tag)
def on_open(connection):
connection.channel(on_open_callback=on_channel_open)
def on_channel_open(channel):
channel.basic_consume(on_message_callback = callback, queue='q1')
channel.basic_consume(on_message_callback = callback, queue='q2')
credentials = pika.PlainCredentials('user', 'password', erase_on_connect=False)
params = pika.ConnectionParameters("localhost", 5672, '/', credentials)
connection = pika.SelectConnection(parameters=params,
on_open_callback=on_open)
try:
connection.ioloop.start()
except KeyboardInterrupt:
connection.close()
connection.ioloop.start()
回调中两条打印行的输出是:
<class 'pika.spec.Basic.Deliver'>
<Basic.Deliver(['consumer_tag=ctag1.2607da3f5f9f4e5592991a16cc0aca6e', 'delivery_tag=1', 'exchange=gatekeeper', 'redelivered=True', 'routing_key=laa'])>
如何提取 'routing_key'?查看源代码后,我相信 method.get_properties()
会起作用,但事实并非如此。
虽然记录不完整,但 callback
函数将使用 4 个参数调用:
- 您使用的频道
- 一个
Method
实例(在本例中是一个Deliver
实例) - 一个
BasicProperties
实例 - 一具尸体(
bytes
)
Deliver
实例将有一个名为 routing_key
的属性。所以你的函数看起来像这样:
def callback(channel, method, properties, body):
print(method.get_body())
print(method.get_properties())
print(method.routing_key)
channel.basic_ack(delivery_tag=method.delivery_tag)
PS。将调用回调的参数与 here 中描述的相同,其中 是 实际记录的。