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)));
        }
    }

结果:
rabbitmq实战系列5--实现 消息确认机制_第1张图片

你可能感兴趣的:(消息队列,rabbitmq,java,队列,spring,boot)