Spring Boot整合RabbitMQ,监听队列获取消息

Spring Boot整合RabbitMQ,监听队列获取消息

1、pom.xml添加如下依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

2、整合rabbitMQ

1、首先建MQConn实体类
/**
 * rabbitMQ的实体类ip、端口号、用户名、密码
 *
 **/
public class MQConn {

    private String host;
    private int port;
    private String username;
    private String password;
    private long connectionTimeout;
    private CachingConnectionFactory.CacheMode cacheMode;
    private int channelCacheSize;
    private long channelCheckoutTimeout;

    省略getter、setter
}

2、建立配置文件rabbitmq.properties
file.rabbitmq.host=192.168.203.136
file.rabbitmq.port=5672
file.rabbitmq.username=chai
file.rabbitmq.password=123456
file.rabbitmq.connectionTimeout=3000

3、注入参数RabbitConfig
@Configuration
@PropertySource("classpath:rabbitmq.properties")
public class RabbitMQConfig {

    // 注入到实体MQConn
    @Bean("mqConn")
    @ConfigurationProperties(prefix = "file.rabbitmq")
    public MQConn fileWorkRabbitFactory(){
        MQConn mqConn=new MQConn();
        return mqConn;
    }

    @Bean("cachingConnectionFactory")
    public CachingConnectionFactory connectionFactory(
            @Qualifier("mqConn") MQConn mqConnFile
    ){
        CachingConnectionFactory cachingConnectionFactory=new CachingConnectionFactory();
        cachingConnectionFactory.setHost(mqConnFile.getHost());
        cachingConnectionFactory.setPort(mqConnFile.getPort());
        cachingConnectionFactory.setUsername(mqConnFile.getUsername());
        cachingConnectionFactory.setPassword(mqConnFile.getPassword());
        cachingConnectionFactory.setVirtualHost("/");
        cachingConnectionFactory.setPublisherConfirms(true);
        if(mqConnFile.getCacheMode()!=null){
            cachingConnectionFactory.setCacheMode(mqConnFile.getCacheMode());
        }
        if(mqConnFile.getChannelCacheSize()>0){
            cachingConnectionFactory.setChannelCacheSize(mqConnFile.getChannelCacheSize());
        }
        if(mqConnFile.getChannelCheckoutTimeout()>0){
            cachingConnectionFactory.setChannelCheckoutTimeout(mqConnFile.getChannelCheckoutTimeout());
        }
        return cachingConnectionFactory;
    }

    @Bean
    @Scope("prototype")
    public PackMsgReceiver packMsgReceiver(){
        return new PackMsgReceiver();
    }

    /**
     * 创建监听器,监听队列
     * @param packMsgReceiver 监听方法
     * @return 监听器
     */
    @Bean
    public SimpleMessageListenerContainer messageListenerContainer(PackMsgReceiver packMsgReceiver, @Qualifier("cachingConnectionFactory") CachingConnectionFactory cachingConnectionFactory){
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cachingConnectionFactory);
        // 监听队列的名称
        container.setQueueNames("hi");
        container.setExposeListenerChannel(true);
        // 设置每个消费者获取的最大消息数量
        container.setPrefetchCount(100);
        // 消费者的个数
        container.setConcurrentConsumers(1);
        // 设置确认模式为手工确认
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        container.setMessageListener(packMsgReceiver);
        return container;
    }
}

4、接收消息处理
@Component
public class PackMsgReceiver implements ChannelAwareMessageListener {
    private static final Logger logger = LoggerFactory.getLogger(PackMsgReceiver.class);

    /**
     * @param 
     * 1、处理成功,这种时候用basicAck确认消息;
     * 2、可重试的处理失败,这时候用basicNack将消息重新入列;
     * 3、不可重试的处理失败,这时候使用basicNack将消息丢弃。
     * 
     *  basicNack(long deliveryTag, boolean multiple, boolean requeue)
     *  deliveryTag:该消息的index
     *  multiple:是否批量.true:将一次性拒绝所有小于deliveryTag的消息。
     *  requeue:被拒绝的是否重新入队列
     */
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        byte[] body = message.getBody();
        logger.info("接收到消息:" + new String(body));
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONObject.parseObject(new String(body));
            if (消费成功) {
                logger.info("消息消费成功");

               channel.basicAck(message.getMessagePropertites().getDeliveryTag(),false);//确认消息消费成功     

            }else if(可重试的失败处理){

                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);

          } else { //消费失败             

               channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);              
        } catch (JSONException e) {
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);//消息丢弃
            logger.error("This message:" + jsonObject + " conversion JSON error ");
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值