rabbit 发送回调信息和异常重试

版本说明: 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: 因其接收消息需要等待,所以吞吐量注定差,且其容易超时,建议使用时设置超时时间长点。


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值