RabbitMQ:监听实现rmq的消息接收

本文详细介绍了RabbitMQ的常用命令,包括启动、关闭、访问控制台等,并展示了如何通过YAML配置文件进行消息监听的实现,包括主题交换和扇出交换的配置,以及不同监听器的创建和启动。此外,还提供了添加用户和设置权限的步骤。
摘要由CSDN通过智能技术生成

https://blog.csdn.net/qq_35387940/article/details/100514134

rabbitMQ常用命令

1.启动rabbitmq
rabbitmqctl start_app
2.开启web控制台的访问
rabbitmq-plugins enable rabbitmq_management
3.访问
http://127.0.0.1:15672/
4.输入用户名密码
默认:guest guest

5.关闭rabbitmq:
rabbitmqctl stop_app
6.还原
rabbitmqctl reset
7.添加用户
rabbitmqctl add_user root root
8.设置权限
rabbitmqctl set_permissions -p / root “.*” “.*” “.*”
9.查看用户
rabbitmqctl list_users

监听实现rmq的消息接收

1.application.yml

spring:
  rabbitmq:
    username: guest
    password: guest
    port: 5672
    addresses: localhost
    virtual-host: 

2.配置amqp.yml

destination:
  fanouts:
    Servertest:
      exchange: test.fanout
      routing-key:
  topics:
    ClientTest:
      exchange: amq.topic
      routing-key: Abc
    MyTest:
      exchange: amq.topic
      routing-key: 1*.#

3.启动加载类Queue2Repository

package com.lit.initialize;
@Component
public class Queue2Repository implements ApplicationRunner {
    private AmqpConfig amqpConfig;
    private AmqpAdmin amqpAdmin;
    private MessageListenerContainerFactory messageListenerContainerFactory;
    private MessageListenerFactory messageListenerFactory;
    @Autowired
    public Queue2Repository(AmqpAdmin amqpAdmin, AmqpConfig amqpConfig, MessageListenerContainerFactory messageListenerContainerFactory) {
        this.amqpAdmin = amqpAdmin;
        this.amqpConfig = amqpConfig;
        this.messageListenerContainerFactory = messageListenerContainerFactory;
    }
    @Autowired
    public void setMessageResolveFactory(MessageListenerFactory messageListenerFactory) {
        this.messageListenerFactory = messageListenerFactory;
    }
    @Override
    public void run(ApplicationArguments args) {
    //获取yml配置信息,配置对应的监听器
        amqpConfig.getTopic().forEach((name, destination) -> {
        			Queue topicQueue = createTopicQueue(name, destination);
                    try {
                        MessageListenerContainer mlc = messageListenerContainerFactory.createMessageListenerContainer(name);
                        MessageListener listener = messageListenerFactory.getInstance(name);
                        if (listener != null) {
                            mlc.setupMessageListener(listener);
                            mlc.start();
                        }
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
        );
        amqpConfig.getFanouts().forEach((name, destination) -> {
        			Queue fanoutQueue = createFanoutQueue(name, destination);
                    try {
                        MessageListenerContainer mlc = messageListenerContainerFactory.createMessageListenerContainer(name);
                        MessageListener listener = messageListenerFactory.getInstance(name);
                        if (listener != null) {
                            mlc.setupMessageListener(listener);
                            mlc.start();
                        }
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
        );
    }
    private Queue createTopicQueue(String name, AmqpConfig.DestinationInfo d){
        Exchange ex = ExchangeBuilder.topicExchange(d.getExchange()).durable(true).build();
        amqpAdmin.declareExchange(ex);
        Queue q = QueueBuilder.durable(name).build();
        amqpAdmin.declareQueue(q);
        Binding b = BindingBuilder.bind(q)
                .to(ex)
                .with(d.getRoutingKey())
                .noargs();
        amqpAdmin.declareBinding(b);
        return q;
    }
    private Queue createFanoutQueue(String name, AmqpConfig.DestinationInfo d){
        Exchange ex = ExchangeBuilder.fanoutExchange(d.getExchange()).durable(true).build();
        amqpAdmin.declareExchange(ex);
        Queue q = QueueBuilder.durable(name).build();
        amqpAdmin.declareQueue(q);
        Binding b = BindingBuilder.bind(q)
                .to(ex)
                .with(d.getRoutingKey())
                .noargs();
        amqpAdmin.declareBinding(b);
        return q;
    }
}

4.配置类 AmqpConfig、MessageListenerContainerFactory、YamlPropertySourceFactory

package com.lit.config;
@Component
@ConfigurationProperties(prefix = "destinations")
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:amqp.yml")
public class AmqpConfig {
    private Map<String, DestinationInfo> topic = new HashMap<>();
    private Map<String, DestinationInfo> fanouts = new HashMap<>();
    public Map<String, DestinationInfo> getTopic() {
        return topic;
    }
    public void setTopic(Map<String, DestinationInfo> topic) {
        this.topic = topic;
    }
    public Map<String, DestinationInfo> getFanouts() {
        return fanouts;
    }
    public void setFanouts(Map<String, DestinationInfo> fanouts) {
        this.fanouts = fanouts;
    }
    public static class DestinationInfo{
        private String exchange;
        private String routingKey;
        public String getExchange() {
            return exchange;
        }
        public void setExchange(String exchange) {
            this.exchange = exchange;
        }
        public String getRoutingKey() {
            return routingKey;
        }
        public void setRoutingKey(String routingKey) {
            this.routingKey = routingKey;
        }
    }
}
package com.lit.config;
@Component
public class MessageListenerContainerFactory {
    private ConnectionFactory connectionFactory;
    public MessageListenerContainerFactory(){
    }
    @Autowired
    public void setConnectionFactory(ConnectionFactory connectionFactory){
        this.connectionFactory = connectionFactory;
    }
    public MessageListenerContainer createMessageListenerContainer(String queueName){
    
        SimpleMessageListenerContainer mlc = new SimpleMessageListenerContainer(connectionFactory);
        //添加队列
        mlc.addQueueNames(queueName);
        //
        mlc.setConcurrency("8");
        //设置签收模式(自动)
        mlc.setAcknowledgeMode(AcknowledgeMode.AUTO);
        return mlc;
    }
}
package com.lit.config;
public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String s, EncodedResource encodedResource) throws IOException {
        String resourceName = Optional.ofNullable(s).orElse(encodedResource.getResource().getFilename());
        if(resourceName.endsWith(".yml")||resourceName.endsWith(".yaml")){
            List<PropertySource<?>> yamlSource = new YamlPropertySourceLoader().load(resourceName,encodedResource.getResource());
            return yamlSource.get(0);
        }else{
            return new PropertiesPropertySource(resourceName,new Properties());
        }
    }
}

5.监听类MessageListenerFactory、Msg1Listener

package com.lit.listener;
@Component
public class MessageListenerFactory {

    public MessageListener getInstance(String queue){
        MessageListener messageListener = null;
        switch (queue){
            case "Servertest":
                messageListener = new Msg1Listener();
                break;
            case "ClientTest":
                messageListener = new Msg2Listener();
                break;
            case "MyTest":
                messageListener = new Msg3Listener();
                break;
            default:
                throw new IllegalStateException("Unexpected value" + queue);
        }
        return messageListener;
    }
}

MsgListener可以写多个分别监听

package com.lit.listener;
@Component
public class Msg1Listener implements MessageListener {

    @Override
    public void onMessage(Message message) {
        try {
            String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
            System.out.println(receivedRoutingKey);
            System.out.println("1");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值