rabbitmq实战系列5--实现 消息确认机制

步骤

1配置yml

spring:
  rabbitmq:
    port: 5672
    host: localhost
    publisher-returns: true         #消息发送失败到消费者失败,是否返回到队列的回调函数
    publisher-confirms: true       #消息从生产者发送到交换机,是否回调
    listener:
      simple:
        acknowledge-mode: manual          #开启手动应答
        concurrency: 10             #并发数,是全局的
        max-concurrency: 15
        prefetch: 6              #单位时间的限流,全局

2配置bean

@Configuration
public class mqConfig1 {
    private static String queue="con_Queue1";
    private static String Exchange="con_Exchange1";
    private static String key="conKey1";
    @Autowired
    CachingConnectionFactory connectionFactory;
    @Bean
    public Queue conQueue(){
        return new Queue(queue);
    }
    @Bean
    public DirectExchange conExchange(){
        return new DirectExchange(Exchange);
    }
    @Bean
    public Binding conBinding(){
        return BindingBuilder.bind(conQueue()).to(conExchange()).with(key);
    }
    @Bean
    public RabbitTemplate rabbitTemplate(){
        //消息发送失败返回队列中,yml相应配置:publisher-return:true;
        RabbitTemplate template=new RabbitTemplate();
        template.setMandatory(true);//开启强制委托模式
        template.setConnectionFactory(connectionFactory);
        template.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            @Override
            public void returnedMessage(Message message, int code, String replyText, String exchange, String routingKey) {
                System.out.println("消息发送到队列失败,原因:"+replyText);
            }
        });
        template.setConfirmCallback((data,ack,cause)->{
            if(ack){
                System.out.println("消息发送到exchange成功,id:"+(data!=null?data.getId():0));
            }else{
                System.out.println("消息发送到exchange失败,原因:"+cause);
            }
        });
        return template;
    }
}

3消费者

@Component
public class listener1 {
    @RabbitListener(queues = "con_Queue1")
    public void hand(Message message, Channel channel) throws IOException {

//手动确认接收消息
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
        System.out.println(Thread.currentThread().getName()+"接受了一条消息:"+new String(message.getBody()));
    }
}


4生产者
注意这里的new CorrelationData,每个发送的消息都需要配备一个 CorrelationData 相关数据对象,CorrelationData 对象内部只有一个 id 属性,用来表示当前消息唯一性。

@Autowired
    RabbitTemplate rabbitTemplate;
    public void test1(){
        for(int i=0;i<10;i++){
            rabbitTemplate.convertAndSend("con_Exchange1","conKey1","str"+i,new CorrelationData(String.valueOf(i)));
        }
    }

结果:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7lobORbP-1587092195953)(https://img-bog.csdnimg.cn/20200417104647989.png)]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值