// Declare a dead letter exchangechannel.exchangeDeclare("${dlxExchangeName}", "direct", true);// Declare an exchange for sending delayed messageschannel.exchangeDeclare("${delayExchangeName}", "direct", true);// Declare a queue for sending delayed messages, and specify its dead letter exchangeMap<String, Object> args = new HashMap<>();args.put("x-dead-letter-exchange", "${dlxExchangeName}");channel.queueDeclare("${delayQueueName}", true, false, false, args);channel.queueBind("${delayQueueName}", "${delayExchangeName}", "");// Declare a dead letter queuechannel.queueDeclare("${delayQueueName}", true, false, false, null);channel.queueBind("${dlxQueueName}", "${dlxExchangeName}", "");// Send delayed messagesint delayInSeconds = 10; // Message delay of 10 secondsAMQP.BasicProperties props = new AMQP.BasicProperties.Builder().expiration(String.valueOf(delayInSeconds * 1000));channel.basicPublish("${delayExchangeName}", "", props.build(), "delayed payload".getBytes());
Parameter | Description |
${dlxExchangeName} | Name of the dead letter exchange for delayed messages. Replace it with the name found in the console's Exchange list. |
${delayExchangeName} | Name of the exchange for sending delayed messages. Replace it with the name found in the console's Exchange list. |
x-dead-letter-exchange | Queue parameter key, which is used to set the dead letter exchange corresponding to the queue. |
${dlxQueueName} | Name of the dead letter queue for delayed messages. |
${delayQueueName} | Name of the queue for sending delayed messages. |
mandatory
, meaning the producer cannot detect unroutable messages through the basic.return
event. Therefore, make sure the corresponding exchanges, queues, and routing relationships exist before delayed messages are sent.++Declare an exchange and specify its route type.Map<String, Object> args = new HashMap<String, Object>();args.put("x-delayed-type", "direct");
The parameters are described as follows: | Parameter |
Description | x-delayed-type Exchange type, which specifies the routing rule. Valid values: direct fanout topic For more information, see |
. | ExchangeName |
Exchange name, which can be obtained from the exchange list in the console. | x-delayed-message |
Send a delayed message. Add a key-value pair (key: x-delay; value: number of milliseconds) to the `Header` attribute of the message and specify the target exchange as the one declared in the previous step.byte[] messageBodyBytes = "delayed payload".getBytes("UTF-8");Map<String, Object> headers = new HashMap<String, Object>();headers.put("x-delay", 4000);AMQP.BasicProperties.Builder props = new AMQP.BasicProperties.Builder().headers(headers);
Was this page helpful?