在direct模式基础上改,但是此次使用注解方式
消费者
修改对应的consumer,用注解方式定义交换机和队列的关系
@Service
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "duanxin.topic.queue",durable = "true",autoDelete = "false"),
exchange = @Exchange(value = "topic_order_exchange",type = ExchangeTypes.TOPIC),
key = "#.duanxin.#"
))
public class TopicDuanxinConsumer {
@RabbitHandler
public void receiveMsg(String msg){
System.out.println("TopicDuanxinConsumer ---接收到的订单信息是:->" + msg);
}
}
@Service
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "email.topic.queue",durable = "true",autoDelete = "false"),
exchange = @Exchange(value = "topic_order_exchange",type = ExchangeTypes.TOPIC),
key = "*.email.#"
))
public class TopicEmailConsumer {
@RabbitHandler
public void receiveMsg(String msg){
System.out.println("TopicEmailConsumer ---接收到的订单信息是:->" + msg);
}
}
@Service
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "sms.topic.queue",durable = "true",autoDelete = "false"),
exchange = @Exchange(value = "topic_order_exchange",type = ExchangeTypes.TOPIC),
key = "com.#"
))
public class TopicSmsConsumer {
@RabbitHandler
public void receiveMsg(String msg){
System.out.println("TopicSmsConsumer ---接收到的订单信息是:->" + msg);
}
}
- 启动SpringbootOrderRabbitmqConsumerApplication,查看交换机队列是否绑定成功
生产者
只需要定义路由规则即可#是任意个,可以有多个,可以有一个,也可以没有;*最少有一个
public void makeOrderTopic(String userId,String productId,int num){
String orderId = UUID.randomUUID().toString();
System.out.println("订单生成成功:" + orderId);
String exchangeName = "topic_order_exchange";
String routingKey = "com.duanxin";
//@param1 交换机 @param2 路由key/queue队列名称 @param3 消息内容
rabbitTemplate.convertAndSend(exchangeName,routingKey,orderId);
}
- 运行测试类
@Test
void contextLoads2() {
orderService.makeOrderTopic("1","1",12);
}
同时客户端也可以收到,当然再次发送也可以收到。
针对于注解方式
虽然简洁,但是还是推荐配置类方式,毕竟各有多爱,另外配置类推荐写在客户端。