How to use RabbitMQ delay queues?

The RabbitMQ delayed queue is achieved through the plugin rabbitmq_delayed_message_exchange, and the following are the steps for using it:

  1. To install the plugin: First, you need to install the rabbitmq_delayed_message_exchange plugin, which can be done by using the following command:
  2. Activate the RabbitMQ Delayed Message Exchange plugin.
  3. Create a delayed exchange: Use the following command to create a delayed exchange:
  4. rabbitmqadmin create a delayed exchange with the name “delayed_exchange”, the type is “x-delayed-message” and the arguments specify the delayed type as “direct”.
  5. Create a delay queue: Use the following command to create a delay queue and bind it to a delay exchange.
  6. Create a queue called “delayed_queue” using rabbitmqadmin and establish a binding between the “delayed_exchange” as the source, the “delayed_queue” as the destination, and using the routing key “delayed_routing_key”.
  7. Send a delayed message: Use the code snippet below to publish a delayed message to the delay queue:
  8. import the Pika library

    establish a connection to the local host using the BlockingConnection method

    create a channel on the established connection

    publish a message with a 5-second delay to the ‘delayed_exchange’ exchange using the ‘delayed_routing_key’ routing key

    close the connection

  9. In the code above, the delay time is specified in milliseconds by setting the x-delay field in the headers.
  10. Consume delayed messages: Use the following code snippet to consume messages in the delayed queue.
  11. Include the ‘pika’ library, define a callback function to print received messages, establish a connection to a local host, create a channel, set up a consumer on a specific queue with automatic acknowledgment, and start consuming messages.
  12. In the above code, by specifying the queue parameter of the basic_consume method as the delay queue name and setting auto_ack to True, the message will be automatically acknowledged.

Please modify the ‘localhost’ and ‘delayed_routing_key’ in the code snippet according to the actual situation.

bannerAds