spring boot整合
生产者依赖
1 <dependencies> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-amqp</artifactId> 5 </dependency> 6 <dependency> 7 <groupId>org.springframework.boot</groupId> 8 <artifactId>spring-boot-starter-test</artifactId> 9 </dependency> 10 </dependencies>
yml配置
1 spring: 2 rabbitmq: 3 host: localhost 4 port: 5672 5 virtual-host: /itcast 6 username: heima 7 password: heima
绑定交换机和队列
1 @Configuration 2 public class RabbitMQConfig { 3 //交换机名称 4 public static final String ITEM_TOPIC_EXCHANGE = "item_topic_exchange"; 5 //队列名称 6 public static final String ITEM_QUEUE = "item_queue"; 7 8 //声明交换机 9 @Bean("itemTopicExchange") 10 public Exchange topicExchange(){ 11 return ExchangeBuilder.topicExchange(ITEM_TOPIC_EXCHANGE).durable(true).build(); 12 } 13 14 //声明队列 15 @Bean("itemQueue") 16 public Queue itemQueue(){ 17 return QueueBuilder.durable(ITEM_QUEUE).build(); 18 } 19 20 //绑定队列和交换机 21 @Bean 22 public Binding itemQueueExchange(@Qualifier("itemQueue") Queue queue, 23 @Qualifier("itemTopicExchange") Exchange exchange){ 24 return BindingBuilder.bind(queue).to(exchange).with("item.#").noargs(); 25 } 26 27 }
消费者依赖
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 <parent> 7 <groupId>org.springframework.boot</groupId> 8 <artifactId>spring-boot-starter-parent</artifactId> 9 <version>2.1.4.RELEASE</version> 10 </parent> 11 <groupId>com.itheima</groupId> 12 <artifactId>springboot-rabbitmq-consumer</artifactId> 13 <version>1.0-SNAPSHOT</version> 14 15 <dependencies> 16 <dependency> 17 <groupId>org.springframework.boot</groupId> 18 <artifactId>spring-boot-starter-amqp</artifactId> 19 </dependency> 20 </dependencies> 21 22 </project>
yml配置
1 spring: 2 rabbitmq: 3 host: localhost 4 port: 5672 5 virtual-host: /itcast 6 username: heima 7 password: heima
消息监听处理类
1 @Component 2 public class MyListener { 3 4 /** 5 * 监听某个队列的消息 6 * @param message 接收到的消息 7 */ 8 @RabbitListener(queues = "item_queue") 9 public void myListener1(String message){ 10 System.out.println("消费者接收到的消息为:" + message); 11 } 12 }
测试
1 @RunWith(SpringRunner.class) 2 @SpringBootTest 3 public class RabbitMQTest { 4 5 @Autowired 6 private RabbitTemplate rabbitTemplate; 7 8 @Test 9 public void test(){ 10 rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.insert", "商品新增,routing key 为item.insert"); 11 rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.update", "商品修改,routing key 为item.update"); 12 rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.delete", "商品删除,routing key 为item.delete"); 13 } 14 }