11. SpringBoot整合
与SpringBoot整合本文只展示了复杂的Topic模型代码,其他代码可以访问我的Gitee
创建Spring项目,完整的目录结构如下:(与topic有关的我已经标注出来了)

1.导入依赖pom.xml
1 2 3 4 5
   | <dependency>     <groupId>org.springframework.boot</groupId>     <artifactId>spring-boot-starter-amqp</artifactId>     <version>2.3.0.RELEASE</version> </dependency>
   | 
 
2.配置文件application.yml
1 2 3 4 5 6 7 8 9 10 11 12
   | spring:   application:     name: rabbitmq_springboot   rabbitmq:          host: xx.xx.xx.xx      port: 5672     username: admin          password:          virtual-host: /ems
   | 
 
3.测试类(生产者)TestRabbitMQ.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
   | package top.hopestation; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest(classes = RabbitmqSpringbootApplication.class) @RunWith(SpringRunner.class) public class TestRabbitMQ {          @Autowired     private RabbitTemplate rabbitTemplate;
           @Test     public void testTopic(){         rabbitTemplate.convertAndSend("toptics","user.save","hello toptic");     } }
 
   | 
 
4.消费者TopticConsumer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
   | package top.hopestation.toptic; import org.springframework.amqp.rabbit.annotation.Exchange; import org.springframework.amqp.rabbit.annotation.Queue; import org.springframework.amqp.rabbit.annotation.QueueBinding; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component;
 
 
  @Component public class TopticConsumer {    
 
 
      @RabbitListener(bindings = {             @QueueBinding(                     value = @Queue,//创建临时队列                     exchange = @Exchange(value = "toptics",type = "topic"),//绑定交换机                     key = {"user.*"}//指定路由key数组(这里是主题模式,可以使用通配符)             )     })     public void revice1(String message){                  System.err.println("FanoutConsumer1 get message 【 " + message + " 】");     }  	
 
 
      @RabbitListener(bindings = {           @QueueBinding(                   value = @Queue,                   exchange = @Exchange(value = "toptics",type = "topic"),                   key = {"user.#","order.#"}           )     })     public void revice2(String message){         System.err.println("FanoutConsumer2 get message 【 " + message + " 】");     }
  }
 
   |