我正在尝试使用@SentTo
批注将返回值发送到RabbitMQ交易所,如此处的文档所述:https://docs.spring.io/spring-amqp/reference/htmlsingle/#async-annotation-driven-reply
如果我需要设置Herader,则文档说要返回Message<OrderStatus>
并使用MessageBuilder
。
但是,我需要设置correlationId
消息属性,而MessageBuilder
没有办法让我设置属性,只能设置标头。
如何使用@SentTo
注释复制我目前在这里所做的事情?
amqpTemplate.convertAndSend(
amqpRoutingKey,
orderStatus,
message -> {
message.getMessageProperties().setCorrelationId(orderStatus.getCorrelationId().toString());
return message;
}
);
谢谢!
答案 0 :(得分:1)
有这个API:
/**
* Makes this builder's properties builder use a reference to properties.
* @param properties The properties.
* @return this.
*/
public MessageBuilder andProperties(MessageProperties properties) {
或者您也可以得到该MessageBuilder
的结果,然后真正调用message.getMessageProperties().setCorrelationId()
。
更新
好吧,AbstractRabbitListenerContainerFactory
中甚至还有刚刚发布的Spring AMQP的这个API:
/**
* Set post processors that will be applied before sending replies.
* @param beforeSendReplyPostProcessors the post processors.
* @since 2.0.3
*/
public void setBeforeSendReplyPostProcessors(MessagePostProcessor... beforeSendReplyPostProcessors) {
UPDATE2
如果您坚持使用org.springframework.messaging.support.MessageBuilder
,则应在该消息中设置一个AmqpHeaders.CORRELATION_ID
标头,并将其正确映射到CorrelationId
。但是,查看代码不需要这样做:
/**
* Post-process the given response message before it will be sent.
* <p>
* The default implementation sets the response's correlation id to the request message's correlation id, if any;
* otherwise to the request message id.
* @param request the original incoming Rabbit message
* @param response the outgoing Rabbit message about to be sent
*/
protected void postProcessResponse(Message request, Message response) {
String correlation = request.getMessageProperties().getCorrelationId();
if (correlation == null) {
String messageId = request.getMessageProperties().getMessageId();
if (messageId != null) {
correlation = messageId;
}
}
response.getMessageProperties().setCorrelationId(correlation);
}