首页 > 其他分享 >106、商城业务---消息队列---可靠抵达-发送端确认(ReturnCallback)

106、商城业务---消息队列---可靠抵达-发送端确认(ReturnCallback)

时间:2023-02-19 23:33:50浏览次数:53  
标签:RabbitTemplate ack ReturnCallback springframework --- org import 106 public


1、编写配置

# rabbitmq的抵达队列的发送端确认(ReturnCallback)
spring.rabbitmq.publisher-returns=true
# 只要抵达队列,以异步方式优先回调我们这个returnconfirm
spring.rabbitmq.template.mandatory=true

2、在自己的rabbit的配置类中重写rabbitTemplate

package com.gulimall.order.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class MyRabbitConfig {

    private RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制RabbitTemplate
     */
    @PostConstruct //在MyRabbitConfig对象创建完成后执行这个方法
    public void initRabbitTemplate(){
        //设置确认回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * 1、只要消息抵达Broker就ack=true
             * correlationData:当前消息的唯一关联数据(这个是消息的唯一id)
             * ack:消息是否成功收到
             * cause:失败的原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("confirm...correlationData["+correlationData+"]==>ack:["+ack+"]==>cause:["+cause+"]");
            }
        });

        //设置消息发送到队列的回调(只有发送失败才会回调)
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * 只要消息【没有】投递给指定的队列,就触发这个失败回调
             * message:投递失败的消息详细信息
             * replyCode:回复的状态码
             * replyText:回复的文本内容
             * exchange:当时这个消息发给哪个交换机
             * routingKey:当时这个消息用哪个路邮键
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("Fail Message["+message+"]==>replyCode["+replyCode+"]" +
                        "==>replyText["+replyText+"]==>exchange["+exchange+"]==>routingKey["+routingKey+"]");
            }
        });
    }
}

标签:RabbitTemplate,ack,ReturnCallback,springframework,---,org,import,106,public
From: https://www.cnblogs.com/morehair/p/17135948.html

相关文章