rabbitMq可靠性投递

   @Bean
    public RabbitTemplate rabbitTemplate(CachingConnectionFactory factory) {
//若使用confirm-callback ,必须要配置publisherConfirms 为true
        factory.setPublisherReturns(true);
        //若使用return-callback,必须要配置publisherReturns为true
        factory.setPublisherReturns(true);
        RabbitTemplate rabbitTemplate = new RabbitTemplate(factory);
        //使用return-callback时必须设置mandatory为true,或者在配置中设置mandatory-expression的值为true
        rabbitTemplate.setMandatory(true);

        // 如果消息没有到exchange,则confirm回调,ack=false; 如果消息到达exchange,则confirm回调,ack=true
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if(ack){
                    System.out.println("消息发送成功:correlationData({}),ack({}),cause({})"+correlationData+":"+ack+":"+cause);
                }else{
                    System.out.println("消息发送成功:correlationData({}),ack({}),cause({})"+correlationData+":"+ack+":"+cause);
                }
            }
        });

        //如果exchange到queue成功,则不回调return;如果exchange到queue失败,则回调return(需设置mandatory=true,否则不回回调,消息就丢了)
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                System.out.println("消息丢失:exchange({}),route({}),replyCode({}),replyText({}),message:{}"+JSON.toJSONString(returnedMessage));
            }
        });
        return rabbitTemplate;
    }

 

上一篇:解决 Duplicate keys detected: ‘483‘. This may cause an update error. 报错问题


下一篇:Cause: java.sql.SQLException: sql injection violation, syntax error: syntax error, expect ‘)‘