概念
image.png实现
根据图我们看出路由的的类型为direct
实现步骤为:
生产者->声明路由(direct)->声明2个队列- >路由分别绑定这2个队列并分别绑定routingkey->发送带routingkey的消息
消费者->监听这2个队列的消息
生产者实现
声明路由注意类型
//声明路由注意路由的类型为direct
@Bean
Exchange exchange(){
return ExchangeBuilder.directExchange("ethan.exchange_routing").build();
}
声明队列
//声明队列
@Bean("queue")
Queue queue(){
return QueueBuilder.durable("queue_routing").build();
}
//声明队列1
@Bean("queue01")
Queue queue01(){
return QueueBuilder.durable("queue_routing_01").build();
}
路由绑定队列这里我们一个队列设置routingkey为error另外一个设置一个error一个info
//绑定队列1到路由并设置routingkey为routing_inforouting_error
@Bean
Binding binding01(@Qualifier("queue01") Queue queue,
Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("routing_error").noargs();
}
//绑定队列1到路由并设置routingkey为routing_info
@Bean
Binding binding02(@Qualifier("queue01") Queue queue,
Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("routing_info").noargs();
}
发送一个error消息一个info消息
@Autowired
MyBean myBean;
@Test
void test(){
myBean.getAmqpTemplate().convertAndSend("ethan.exchange_routing","routing_error","error-----");
myBean.getAmqpTemplate().convertAndSend("ethan.exchange_routing","routing_info","info------");
}
期望达到的结果为发送到error的routingkey2个队列都能收到消息,发送带info的只有一个队列可以收到消息
消费者
@Component
@Slf4j
public class ReceiverBean {
@RabbitListener(queues = "queue_routing")
public void processMessage(String msg) {
log.info("queue_routing---"+msg);
}
@RabbitListener(queues = "queue_routing_01")
public void processMessage01(String msg) {
log.info("queue_routing_01---"+msg);
}
}
运行效果
image.png可以看出运行效果和期待的一样
代码
生产端
https://gitee.com/ethanlab/rabbitmq/tree/master/rabbit-routing-producer
消费端
https://gitee.com/ethanlab/rabbitmq/tree/master/rabbit-routing-consumer
网友评论