在SpringBoot应用中使用MQ

一、在SpringBoot应用中使用MQ

SpringBoot应用可以完成自动配置及依赖注入——可以通过Spring直接提供与MQ的连接对象

1.1 消息生产者

  • 创建SpringBoot应用,添加依赖

    image-20200525163617224
  • 配置application.yml

    server:
      port: 9001
    spring:
      application:
        name: producer
      rabbitmq:
        host: 47.96.11.185
        port: 5672
        virtual-host: host1
        username: ytao
        password: admin123
    
  • 发送消息

    @Service
    public class TestService {
    
        @Resource
        private AmqpTemplate amqpTemplate;
    
        public void sendMsg(String msg){
    
            //1. 发送消息到队列
            amqpTemplate.convertAndSend("queue1",msg);
    
            //2. 发送消息到交换机(订阅交换机)
            amqpTemplate.convertAndSend("ex1","",msg);
    
            //3. 发送消息到交换机(路由交换机)
            amqpTemplate.convertAndSend("ex2","a",msg);
            
        }
    
    }
    

1.2 消息消费者

  • 创建项目添加依赖

  • 配置yml

  • 接收消息

    @Service
    //@RabbitListener(queues = {"queue1","queue2"})
    @RabbitListener(queues = "queue1")
    public class ReceiveMsgService {
    
        @RabbitHandler
        public void receiveMsg(String msg){
            System.out.println("接收MSG:"+msg);
        }
    
        //@RabbitHandler
        //public void receiveMsg(byte[] bs){
        //
        //}
    
    }
    
posted @ 2021-01-07 14:04  codeFiler  阅读(528)  评论(0编辑  收藏  举报