问题描述
我想要两套 API 供客户端发布消息
- 同步发送(不重试,立即失败并将状态同步发送回客户端)
- 异步发送(发布者和确认回调,重试,在某些重试后记录并删除消息)。我可以通过启用确认和返回来实现这一点。
有没有办法使用rabbitTemplate实现同步发布API,它会阻止确认并返回两者?
rabbiTemplate.waitForConfirmsOrDie(mills) 阻止确认,但我希望调用者知道路由是否成功或抛出异常。
解决方法
从 RabbitOeprations
查看此 API:
/**
* Send a message to a specific exchange with a specific routing key.
*
* @param exchange the name of the exchange
* @param routingKey the routing key
* @param message a message to send
* @param correlationData data to correlate publisher confirms.
* @throws AmqpException if there is a problem
*/
void send(String exchange,String routingKey,Message message,CorrelationData correlationData)
返回或确认在提供的 CorrelationData
中最后设置。您必须等待其 getFuture()
,然后将您针对 Confirm
原因做出的决定返回给调用方。请参阅该 CorrelationData
JavaDocs 及其实现中的更多信息。另请参阅有关此事的一些文档:https://docs.spring.io/spring-amqp/docs/current/reference/html/#template-confirms
我正在使用以下内容:
rabbitTemplate.convertAndSend(exchange,key,obj,correlationData);
SettableListenableFuture<CorrelationData.Confirm> future = correlationData.getFuture();
CorrelationData.Confirm confirm = future.get();
然后用同样的方法检查。
if(!confirm .isAck() || correlationData.getReturnedMessage() != null){
// throw exception
}