Table of contents
2. Create queues and virtual machines
1. Build the project
Introduce related dependencies and write configuration files
Configuration file:
spring: rabbitmq: host: 192.168.66.130 port: 5672 username: root password: root virtual-host: / #日志格式 logging: pattern: console: '%d{HH:mm:ss.SSS} %clr(%-5level) --- [%-15thread] %cyan(%-50logger{50}):%msg%n'
Related dependencies:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.amqp</groupId> <artifactId>spring-rabbit-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2. Create queues and virtual machines
It must be noted that the creation of virtual machines and queues is in the configuration class, and the switch type changes according to the return value type
package com.example.demo; import org.springframework.amqp.core.*; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class SpringConfig { //交换机名字 private final String exchange_name="exchange_one"; //队列名字 private final String queue_name="queue_one"; //创建交换机 @Bean("bootexchange") public Exchange getexchange(){ //想换交换机类型 //返回值可以写成DirectExchange //TopicExchange等等 return ExchangeBuilder .topicExchange(exchange_name)//交换机名字 .durable(true)//是否持久化 .build(); } //创建队列 @Bean("bootqueue") public Queue getqueue(){ return new Queue(queue_name);//队列名 } //交换机绑定队列 @Bean public Binding bingmessagequeue(@Qualifier("bootexchange") Exchange exchange, @Qualifier("bootqueue") Queue queue){ return BindingBuilder .bind(queue) .to(exchange) .with("#.mess.#") .noargs(); } }
3. Write the producer
The producer's sending information does not need to be so cumbersome, you can directly use the provided tools
package com.example.demo; import org.junit.jupiter.api.Test; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class TestProducer { //注入rabbittemplate工具类 @Autowired private RabbitTemplate rabbitTemplate; @Test public void send(){ //参数一是交换机 //参数二是路由键 //参数三表示要发送的信息 rabbitTemplate.convertAndSend("exchange_one","mess","我要开始发送信息了"); } }
Fourth, write consumers
The consumer code should not be in the same project as the producer
package com.example.rabbitmq2; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class consumer { @RabbitListener(queues ="queue_one") public void listen(String m){ System.out.println("接收到的信息="+m); } }