How can I use Pika to send and receive RabbitMQ messages?

I have a problem with Pika working with routing keys or exchanges in accordance with the AMQP or RabbitMQ documentation. I understand that the RabbitMQ documentation uses an earlier version of Pika, so I ignored their sample code.

What I'm trying to do is define a queue, an "order" and have two consumers that handle the exchange or routing_key "production", and one that processes the "test". From a look at this documentation, RabbitMQ, which should be fairly easy to do, using the direct exchange and routing keys or using a topic exchange.

However, Pika does not know what to do with the exchange and routing keys. Using the RabbitMQ management tool to check the queues, it is pretty obvious that Pika either did not queue the message correctly, or that RabbitMQ just threw it away.

On the consumer side, it’s not entirely clear how I should tie the user to an exchange or handle routing keys, and the documentation does not really help.

If I drop all ideas or exchanges and routing keys, the messages will look beautiful and easily processed by my consumer.

Any pointers or examples of people code would be nice.

+4
source share
1 answer

As it turned out, my understanding of AMQP was incomplete.

The idea is as follows:

Client

After receiving the connection, the client should not care about anything other than the exchange name and the routing key. That is, we do not know in which queue this will end.

channel.basic_publish(exchange='order', routing_key="order.test.customer", body=pickle.dumps(data), properties=pika.BasicProperties( content_type="text/plain", delivery_mode=2)) 

Consumer

When the channel is open, we announce the exchange and queue

 channel.exchange_declare(exchange='order', type="topic", durable=True, auto_delete=False) channel.queue_declare(queue="test", durable=True, exclusive=False, auto_delete=False, callback=on_queue_declared) 

When the queue is ready, this is a good place in the on_queue_declared callback, we can bind the queue to the exchange using our desired routing key.

 channel.queue_bind(queue='test', exchange='order', routing_key='order.test.customer') #handle_delivery is the callback that will actually pickup and handle messages #from the "test" queue channel.basic_consume(handle_delivery, queue='test') 

Messages sent to the "order" exchange with the routing key, "order.test.customer" will now be redirected to the "test" queue, where the consumer can pick it up.

+11
source

Source: https://habr.com/ru/post/1345414/


All Articles