Delayed Message Exchange

版本 1.6 引入了对 Delayed Message Exchange Plugin 的支持。

Version 1.6 introduces support for the Delayed Message Exchange Plugin

该插件目前标记为实验性,但已推出一年多(在撰写本文时)。如果插件更改确实有必要,我们计划尽快添加对此类更改的支持。因此,Spring AMQP 中的此支持也应被视为实验性的。此功能已通过 RabbitMQ 3.6.0 和插件的 0.0.1 版本进行了测试。

The plugin is currently marked as experimental but has been available for over a year (at the time of writing). If changes to the plugin make it necessary, we plan to add support for such changes as soon as practical. For that reason, this support in Spring AMQP should be considered experimental, too. This functionality was tested with RabbitMQ 3.6.0 and version 0.0.1 of the plugin.

要使用 RabbitAdmin 将交换声明为延迟,你可以将交换 bean 上的 delayed 属性设置为 trueRabbitAdmin 会使用交换类型(DirectFanout 等)设置 x-delayed-type 参数,并声明交换类型为 x-delayed-message

To use a RabbitAdmin to declare an exchange as delayed, you can set the delayed property on the exchange bean to true. The RabbitAdmin uses the exchange type (Direct, Fanout, and so on) to set the x-delayed-type argument and declare the exchange with type x-delayed-message.

使用 XML 配置交换 bean 时,也可以使用 delayed 属性(默认:false)。以下示例显示了如何使用它:

The delayed property (default: false) is also available when configuring exchange beans using XML. The following example shows how to use it:

<rabbit:topic-exchange name="topic" delayed="true" />

要发送延迟消息,你可以通过 MessageProperties 设置 x-delay 头,如下例所示:

To send a delayed message, you can set the x-delay header through MessageProperties, as the following examples show:

MessageProperties properties = new MessageProperties();
properties.setDelay(15000);
template.send(exchange, routingKey,
        MessageBuilder.withBody("foo".getBytes()).andProperties(properties).build());
rabbitTemplate.convertAndSend(exchange, routingKey, "foo", new MessagePostProcessor() {

    @Override
    public Message postProcessMessage(Message message) throws AmqpException {
        message.getMessageProperties().setDelay(15000);
        return message;
    }

});

要检查是否延迟了消息,请在 MessageProperties 上使用 getReceivedDelay() 方法。这是一个单独的属性,可避免意外传播到从输入消息生成输出消息。

To check if a message was delayed, use the getReceivedDelay() method on the MessageProperties. It is a separate property to avoid unintended propagation to an output message generated from an input message.