Alternative Mechanism for Publisher Confirms and Returns

当为发布确认和退信配置连接工厂时,以上部分讨论了配置用于异步接收确认和退信的消息通道。从 5.4 版开始,还有一种新机制,该机制通常更容易使用。

When the connection factory is configured for publisher confirms and returns, the sections above discuss the configuration of message channels to receive the confirms and returns asynchronously. Starting with version 5.4, there is an additional mechanism which is generally easier to use.

在这种情况下,请勿配置 confirm-correlation-expression、确认和退信通道。相反,在 AmqpHeaders.PUBLISH_CONFIRM_CORRELATION 标头中添加 CorrelationData 实例;然后可以通过检查已发送消息的 CorrelationData 实例中 future 的状态来稍后等待结果。如果在 future 完成之前,将始终填充 returnedMessage 字段(如果消息被退回)。

In this case, do not configure a confirm-correlation-expression or the confirm and return channels. Instead, add a CorrelationData instance in the AmqpHeaders.PUBLISH_CONFIRM_CORRELATION header; you can then wait for the result(s) later, by checking the state of the future in the CorrelationData instances for which you have sent messages. The returnedMessage field will always be populated (if a message is returned) before the future is completed.

CorrelationData corr = new CorrelationData("someId"); // <--- Unique "id" is required for returns
someFlow.getInputChannel().send(MessageBuilder.withPayload("test")
        .setHeader("rk", "someKeyThatWontRoute")
        .setHeader(AmqpHeaders.PUBLISH_CONFIRM_CORRELATION, corr)
        .build());
...
try {
    Confirm Confirm = corr.getFuture().get(10, TimeUnit.SECONDS);
    Message returned = corr.getReturnedMessage();
    if (returned !- null) {
        // message could not be routed
    }
}
catch { ... }

为了提高性能,您可能希望发送多条消息,然后再等待确认,而不是一次发送一条。退回的消息是转换后的原始消息;您可以使用任何需要附加数据来对 CorrelationData 进行子类化。

To improve performance, you may wish to send multiple messages and wait for the confirmations later, rather than one-at-a-time. The returned message is the raw message after conversion; you can sub-class a CorrelationData with whatever additional data you need.