我正在尝试在 RabbitMQ
basic_consume
方法中传递需要额外参数的回调函数。
例如RabbitMQ中的回调函数签名为:
def callback(ch, method, properties, body):
pass
我想要类似的东西:
def callback(ch, method, properties, body, x, y):
# do something with x and y
然后在
basic_consume
中将其作为回调传递下来
channel.queue_declare(queue=queue_name, durable=True)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue=queue_name, on_message_callback=callback)
channel.start_consuming()
我怎样才能实现这样的目标?
您可以使用 currying 生成回调:
def generateCallback(x, y):
def callback(ch, method, properties, body):
print(
"callback for ch={}, method={}, properties={}, body={}, x={}, y={} called".format(
ch, method, properties, body, x, y
)
)
return callback
if __name__ == "__main__":
callback = generateCallback(1, 2)
callback("ch", "method", "properties", "body")
输出:
callback for ch=ch, method=method, properties=properties, body=body, x=1, y=2 called
@user11044402 在 https://stackoverflow.com/a/57990101/7097311 的回答非常有帮助。
稍微改变一下答案。要使代码按要求工作:
callback = generateCallback(1, 2)
channel.basic_consume(queue=queue,
on_message_callback=callback,
auto_ack=True)