Springamqp rabbit json ReturnCallback ConfirmCallback

本文介绍了如何在Spring Boot应用中集成RabbitMQ,使用Jackson2JsonMessageConverter进行JSON消息转换,并实现ConfirmCallback和ReturnCallback,确保消息的发送与接收确认,以及异常处理。示例代码展示了配置RabbitTemplate、创建监听容器工厂以及发送与接收消息的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

package com.study.soufang.rabbit.a003.springboot.rabbitmq;

import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.support.CorrelationData;

public class MyConfirmCallback implements ConfirmCallback {

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        // TODO Auto-generated method stub
        System.out.println("correlationData:"+correlationData+",ACK:"+ack+",Cause:"+cause);
    }

}
--------------------------------------------------------------------------------------------------------------------------------------------

package com.study.soufang.rabbit.a003.springboot.rabbitmq;

import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.PropertyMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyRabbitConfiguration {

    private RabbitProperties properties;
    MessageConverter messageConverter = new Jackson2JsonMessageConverter();
    @Bean
    @ConditionalOnMissingBean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        PropertyMapper map = PropertyMapper.get();
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setConfirmCallback(new MyConfirmCallback());
        template.setReturnCallback(new MyReturnCallback());
        template.setMessageConverter(messageConverter);
        //mandatory 默认为FALSE,如果exchange根据自身类型和消息routeKey无法找到一个符合条件的queue,会直接将消息扔掉
        template.setMandatory(true);
        return template;
    }
    
    
    @Bean(name = "rabbitListenerContainerFactory")
    @ConditionalOnMissingBean(name = "rabbitListenerContainerFactory")
    @ConditionalOnProperty(prefix = "spring.rabbitmq.listener", name = "type", havingValue = "simple", matchIfMissing = true)
    public SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer,
            ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        factory.setMessageConverter(messageConverter);
        return factory;
    }
    
}
--------------------------------------------------------------------------------------------------------------------------------------------------------

package com.study.soufang.rabbit.a003.springboot.rabbitmq;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;

public class MyReturnCallback implements ReturnCallback {

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println("Message : "+ message);
        System.out.println("replyCode : "+ replyCode);
        System.out.println("replyText : "+ replyText);
        System.out.println("exchange : "+ exchange);
        System.out.println("routingKey : "+ routingKey);
    }

}
 

------------------------------------------------------------------------------------------------------------------------------------------------------------------

package com.study.soufang.rabbit.a003.springboot.rabbitmq;

import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class TestRecv {

    @RabbitListener(queuesToDeclare=@Queue("springboot.rabbit.test.simple.queue"))
    public void processMessage(User user) throws Exception {
        System.out.println("---------"+user);
    }
    
}
 

------------------------------------------------------------------------------------------------------------------------------------------------------------------

package com.study.soufang.rabbit.a003.springboot.rabbitmq;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpAdmin;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TestSend {

    @Autowired
    AmqpAdmin amqpAdmin;
    @Autowired
    AmqpTemplate amqpTemplate;
    
    public void send(){
        String queueName = "springboot.rabbit.test.simple.queue";
        //注意默认队列是持久化的
        amqpAdmin.declareQueue(new Queue(queueName));
        /**
         * mandatory 默认为FALSE,如果exchange根据自身类型和消息routeKey无法找到一个符合条件的queue,会直接将消息扔掉
         * 发送过程中RabbitServer挂掉,会直接报错 Connection refused: connect
         */

        //默认消息持久化发送
        amqpTemplate.convertAndSend("",queueName, new User().setId(14).setName("中文"));

       //发送非持久化消息,RabbitServer重启后,消息丢失
        amqpTemplate.convertAndSend(queueName, new User().setId(14).setName("中文"), new MessagePostProcessor() {
            
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
                return message;
            }
        });
    }
    
}

------------------------------------------------------------------------------------------------------------------------------------------------------------------

package com.study.soufang.rabbit.a003.springboot.rabbitmq;

import java.io.Serializable;

import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain=true)
public class User implements Serializable{

    private Integer id;
    private String name;
    
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值