rabbitMQ五种消息发送模式——路由模式
紧接上一篇:https://blog.csdn.net/qq_36357242/article/details/107686056
本篇介绍路由模式
路由模式
路由模式是可以根据路由键
选择性给多个消费者发送消息的模式,它包含一个生产者、两个消费者、两个队列和一个交换机。两个消费者同时绑定到不同的队列上去,两个队列通过路由键
绑定到交换机上去,生产者发送消息到交换机,交换机通过路由键
转发到不同队列,队列绑定的消费者接收并消费消息。
声明交换机和队列
//声明路由模式交换机
@Bean
public DirectExchange direct() {
return new DirectExchange("exchange.direct");
}
//申明俩个路由模式队列
@Bean
public Queue directQueue1() {
return new Queue("direct1"); //队列一
}
@Bean
public Queue directQueue2() {
return new Queue("direct2"); //队列二
}
//将队列队列一绑定到交换机
@Bean
public Binding directBinding1a(DirectExchange direct, Queue directQueue1) {
return BindingBuilder.bind(directQueue1).to(direct).with("orange");
}
@Bean
public Binding directBinding1b(DirectExchange direct, Queue directQueue1) {
//
return BindingBuilder.bind(directQueue1).to(direct).with("black");
}
//将队列队列二绑定到交换机
@Bean
public Binding directBinding2a(DirectExchange direct, Queue directQueue2) {
return BindingBuilder.bind(directQueue2).to(direct).with("green");
}
@Bean
public Binding directBinding2b(DirectExchange direct, Queue directQueue2) {
return BindingBuilder.bind(directQueue2).to(direct).with("black");
}
创建生产者(发送者)
//创建消息发送者
public void sendToDirect() {
String context = "路由模式发送的消息";
System.out.println("路由模式发送者: " + context);
//走black路由
this.rabbitTemplate.convertAndSend("exchange.direct", "black",context);
//走orange路由
// this.rabbitTemplate.convertAndSend("exchange.direct", "orange",context);
//走green路由
// this.rabbitTemplate.convertAndSend("exchange.direct", "green",context);
}
创建消费者(接收者)
@RabbitListener(queues = "direct1")
@RabbitHandler
public void process6(String direct) {
System.err.println("路由模式 消费者1: " + direct);
}
@RabbitListener(queues = "direct2")
@RabbitHandler
public void process7(String direct) {
System.out.println("路由模式 消费者2: " + direct);
}
运行
//路由模式
@Test
public void contextLoads4() {
for (int i = 0;i<10; i++){
senderConfig.sendToDirect();
}
}
不同的路由自己试一下。
还没有评论,来说两句吧...