版本说明: amqp 2.2.2
yml配置
rabbitmq: host: xxx port: xxx username: xxx password: xxx publisher-confirm-type: correlated #开启确认模式 publisher-returns: true # 开启交换机到队列的回调 也就是下面setReturnCallback template: # 开启重试机制,便于网络等异常原因后的重试 默认3次 retry: enabled: true cache: # 连接和通道数量 channel: size: 30 connection: size: 5 mode: connection
配置类
打印发送到交换机上的情况日志,和交换机到队列失败的回调
@Slf4j @Configuration public class MqConnectionFactory { @Autowired RabbitTemplate rabbitTemplate; @PostConstruct public void init(){ rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> { String id = correlationData==null? null: correlationData.getId(); if (ack) { //消息投递到exchange log.info("消息发送到exchange成功:message_id={} ", id); } else { log.error("消息发送到exchange失败:cause={},message_id={}",cause, id); } }); //设置return callback rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey) -> { // 投递失败,记录日志 log.error("消息发送失败回调信息,应答码{},原因{},交换机{},路由键{},消息{}", replyCode, replyText, exchange, routingKey, message.toString()); }); } }
因我这里只想排查问题时知道是哪个消息id,所以发送时记录id
CorrelationData correlationData = null; if(!ObjectUtils.isEmpty(id) ){ correlationData = new CorrelationData(id); } rabbitTemplate.convertAndSend(exchange, topic, msg,correlationData);
若要想在回调中知道其他信息,可继承CorrelationData,重写对象。再在回调中判断correlationData的类型后处理消息。
convertAndSend和convertSendAndReceive的差异在于,
convertSendAndReceive: 因其接收消息需要等待,所以吞吐量注定差,且其容易超时,建议使用时设置超时时间长点。