生产者
在fanout基础上更改;(只给routeKey是email和duanxin的发)
- 在OrderService添加如下方法
public void makeOrderDirect(String userId,String productId,int num){
String orderId = UUID.randomUUID().toString();
System.out.println("订单生成成功:" + orderId);
String exchangeName = "direct_order_exchange";
// String routingKey = "";
//@param1 交换机 @param2 路由key/queue队列名称 @param3 消息内容
rabbitTemplate.convertAndSend(exchangeName,"email",orderId);
rabbitTemplate.convertAndSend(exchangeName,"duanxin",orderId);
}
- 增加direct的配置类(完成交换机声明以及绑定)
@Configuration
public class DirectRabbitMqConfiguration {
//声明交换机
@Bean
public DirectExchange directExchange(){
return new DirectExchange("direct_order_exchange",true,false);
}
//声明队列
@Bean
public Queue directSmsQueue(){
return new Queue("sms.direct.queue",true);
}
@Bean
public Queue directDuanxinQueue(){
return new Queue("duanxin.direct.queue",true);
}
@Bean
public Queue directEmailQueue(){
return new Queue("email.direct.queue",true);
}
//完成交换机和队列绑定
@Bean
public Binding directSmsBinding(){
return BindingBuilder.bind(directSmsQueue()).to(directExchange()).with("sms");
}
@Bean
public Binding directDuanxinBinding(){
return BindingBuilder.bind(directDuanxinQueue()).to(directExchange()).with("duanxin");
}
@Bean
public Binding directEmailBinding(){
return BindingBuilder.bind(directEmailQueue()).to(directExchange()).with("email");
}
}
- 测试发送查看控制台
@Test
void contextLoads1() {
orderService.makeOrderDirect("1","1",12);
}
- 查看浏览器进入rabbitmq;
可以看到只有duanxin和email收到了消息
- 点进去direct_order_exchange看是否绑定上了routeKey
消费者
- 修改对应的consumer
@Service
@RabbitListener(queues = {"duanxin.direct.queue"})
public class DirectDuanxinConsumer {
@RabbitHandler
public void receiveMsg(String msg){
System.out.println("DirectDuanxinConsumer ---接收到的订单信息是:->" + msg);
}
}
@Service
@RabbitListener(queues = {"email.direct.queue"})
public class DirectEmailConsumer {
@RabbitHandler
public void receiveMsg(String msg){
System.out.println("DirectEmailConsumer ---接收到的订单信息是:->" + msg);
}
}
@Service
@RabbitListener(queues = {"sms.direct.queue"})
public class DirectSmsConsumer {
@RabbitHandler
public void receiveMsg(String msg){
System.out.println("DirectSmsConsumer ---接收到的订单信息是:->" + msg);
}
}
- 启动应用SpringbootOrderRabbitmqConsumerApplication,确实只有email和duanxin收到了
当然生产者再次发送,客户端依然会收到。