目录
1.maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.配置参数
#配置rabbitMq
spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.publisher-returns=true
spring.rabbitmq.publisher-confirm-type=correlated
3.发送消息
@Autowired
private RabbitTemplate rabbitTemplate;
@GetMapping(value = "/testmq")
public void testmq() {
try {
rabbitTemplate.convertAndSend("abc", "aa", JSON.toJSONString("我是1"));
rabbitTemplate.convertAndSend("abc", "bb", JSON.toJSONString("我是2"));
rabbitTemplate.convertAndSend("weather", "bb", JSON.toJSONString("我是3"));
System.out.println("已发送");
} catch (Exception e) {
e.printStackTrace();
}
}
4.接收消息
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "123"), exchange = @Exchange(value = "abc", type = ExchangeTypes.TOPIC), key = "aa"))
@RabbitHandler
public void process3(String message) {
try {
System.out.println("process3:"+message);
} catch (Exception e) {
log.error("MQ--process3--#--收到消息处理异常 : [e]{},[message]{}", e, message);
}
}
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "456"), exchange = @Exchange(value = "abc", type = ExchangeTypes.TOPIC), key = "bb"))
@RabbitHandler
public void process4(String message) {
try {
System.out.println("process4:"+message);
} catch (Exception e) {
log.error("MQ--process4--#--收到消息处理异常 : [e]{},[message]{}", e, message);
}
}
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "4567"), exchange = @Exchange(value = "abc", type = ExchangeTypes.TOPIC), key = "bb"))
@RabbitHandler
public void process42(String message) {
try {
System.out.println("process42:"+message);
} catch (Exception e) {
log.error("MQ--process4--#--收到消息处理异常 : [e]{},[message]{}", e, message);
}
}
@RabbitListener(bindings = @QueueBinding(value = @Queue(value = "456"), exchange = @Exchange(value = "weather", type = ExchangeTypes.TOPIC), key = "bb"))
@RabbitHandler
public void process5(String message) {
try {
System.out.println("process5:"+message);
} catch (Exception e) {
log.error("MQ--process4--#--收到消息处理异常 : [e]{},[message]{}", e, message);
}
}
5.输出结果
6.总结
5.1生产端
方法 rabbitTemplate 的 convertAndSend(String exchange, String routingKey, Object object) 只需要将消息体发到指定的【交换机】和【路由键】上就可以
5.2消费端
注解 @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "123"), exchange = @Exchange(value = "abc", type = ExchangeTypes.TOPIC), key = "aa")) 监听队列名(可自定义) 将队列绑定到想要消费的【交换机】和【路由键】上 如果没有【交换机】和【路由键】就创建。
通过上述测试结果,如果两个监听的消费端绑定的【交换机】和【路由键】一致,则都能收到消息