springboot学习笔记(十) RabbitMQ

springboot学习笔记(十)

整合RabbitMQ

  • 导入 pom 依赖

    
        org.springframework.boot
        spring-boot-starter-parent
        1.5.7.RELEASE
    
    
    
    
        
            org.springframework.boot
            spring-boot-starter
        
    
        
            org.springframework.boot
            spring-boot-starter-web
        
    
        
            org.springframework.boot
            spring-boot-starter-amqp
        
    
        
            org.springframework.boot
            spring-boot-starter-test
        
    
    
    
  • 构建一个程序入口

    @SpringBootApplication
    public class RabbitMQApp {
    
        public static void main(String[] args) {
            new SpringApplicationBuilder(RabbitMQApp.class).build().run(args);
        }
    
    }
    
  • application.yml 文件如下

    spring:
      application: 
        name: rabbitmq-demo
      rabbitmq: 
        host: 192.168.100.201
        port: 5672
        username: root
        password: root
    server:
      port: 8090
    
  • 构建一个消息发送者:

    @Component
    public class Sender {
    
        @Autowired
        private AmqpTemplate rabbitTemplate;
    
        public void send(String message){
            this.rabbitTemplate.convertAndSend("msg",message);
            System.out.println("send a message : " + message + " date: " + new Date());
        }
    }
    
  • 构建一个消息接收者:

    @Component
    @RabbitListener(queues = "msg")
    public class Receiver {
    
        @RabbitHandler
        public void process(String msg){
            System.out.println("Receiver a message : " + msg + " date: " + new Date());
        }
    
    }
    
  • 创建一个测试方法:

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class RabbitTest {
    
        @Autowired
        private Sender sender;
    
        @Test
        public void testRabbit(){
            sender.send("Hello RabbitMQ !");
        }
    
    }
    

-先启动程序入口,再启动测试类
测试类控制台打印:

切回RabbitMQApp控制台发现打印如下数据:

    个人学习springboot博客地址:
    http://blog.csdn.net/forezp/article/details/70341818
    http://blog.didispace.com/Spring-Boot%E5%9F%BA%E7%A1%80%E6%95%99%E7%A8%8B/

你可能感兴趣的:(Spring,Boot)