在前两篇中我分享了一些MQ的基础知识和系统安装,接下来我就围绕着四个不同的交换策略进行代码实操。
这一片主要是针对direct交换机进行讲解。
DirectExchange路由转发策略是将消息队列绑定到一个交换机上,当一条消息到来的时候交换机会根据routingKey转发到queue上进行消息处理。
1、首先我们打开RabbitMQ的可视化界面,点击Queues可以查看当前已有的队列
2、在pom.xml文件中引入相关依赖,并且做相关配置
<properties>
<maven.compiler.source>15</maven.compiler.source>
<maven.compiler.target>15</maven.compiler.target>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
这里我选用的是JDK15和springBoot2.6.4,小伙伴们可以自行更换版本即可。
然后在application文件中配置信息(可以省略,springBoot可以自动帮我们使用默认值配好)
3、创建exchange配置类
@Configuration
public class RabbitDirectConfig {
public static final String DIRECT_NAME= "test-direct";
@Bean
Queue queueOne(){
return new Queue("hi-queue1");
}
@Bean
Queue queueTwo(){
return new Queue("hi-queue2");
}
@Bean
DirectExchange directExchange(){
return new DirectExchange(DIRECT_NAME,true,false);
}
@Bean
Binding bindingOne(){
return BindingBuilder.bind(queueOne())
.to(directExchange()).with("direct1");
}
@Bean
Binding bindingTwo(){
return BindingBuilder.bind(queueTwo())
.to(directExchange()).with("direct2");
}
}
这里提供了两个消息队列,创建了一个交换机实例对象,三个参数的意义是名称、是否持久化、长期未用是否删除。
Binding对象用于将队列和交换机绑定在一起
4、配置消费者实例
@Component
public class DirectReceiverOne {
@RabbitListener(queues = "hi-queue1")
public void handler1(String msg){
System.out.println("从hi-queue1收到消息:"+msg);
}
@RabbitListener(queues = "hi-queue2")
public void handler2(String msg){
System.out.println("从hi-queue2收到消息:"+msg);
}
}
5、测试实例
向队列一发送消息
@SpringBootTest(classes = MainApplication.class)
public class RabbitTests {
@Autowired
private AmqpTemplate amqpTemplate;
@Test
public void directTest(){
amqpTemplate.convertAndSend("hi-queue1","this is to queue1");
}
}
向队列2发送消息
6、总结
笔者认为,当我们想要发送到某一个队列的时候,会经过交换机,然后交换机会通过队列名找到对应的routingKey进行路由转发,从而达到效果。
(若有不正确的地方欢迎指正!)