RabbitMq:SimpleMessageListenerContainer和ChannelAwareMessageListener的配合使用

思路:

1、 在配置类中通过 SimpleMessageListenerContainer 配置监听消息队列的各种参数

2、 自定义一个类实现 ChannelAwareMessageListener 接口


配置类

package com.example.testgetmq.config;

import com.example.testgetmq.controller.MyConsumer;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    @Autowired
    SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory;

    @Bean
    public SimpleMessageListenerContainer test_SimpleRabbitListenerContainerFactory() {
        SimpleMessageListenerContainer simpleMessageListenerContainer =
                simpleRabbitListenerContainerFactory.createListenerContainer();
        simpleMessageListenerContainer.setQueueNames("boot_queue");
        simpleMessageListenerContainer.setConcurrentConsumers(1);
        simpleMessageListenerContainer.setMaxConcurrentConsumers(5);
        //设置是否重回队列
        simpleMessageListenerContainer.setDefaultRequeueRejected(false);
        //设置自动签收
        simpleMessageListenerContainer.setAcknowledgeMode(AcknowledgeMode.AUTO);
        //设置监听外露
        simpleMessageListenerContainer.setExposeListenerChannel(true);

//        将实现了ChannelAwareMessageListener接口的MyConsumer类的实例传进setMessageListener中
        simpleMessageListenerContainer.setMessageListener(new MyConsumer());

        return simpleMessageListenerContainer;

    }


}

实现 ChannelAwareMessageListener 接口

package com.example.testgetmq.controller;


import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;


public class MyConsumer implements ChannelAwareMessageListener {

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        System.out.println("我的方法呀:" + message);
    }

}

posted @ 2021-05-25 14:46  西红柿里没有番茄  阅读(2004)  评论(0编辑  收藏  举报