4.RabbitMq主题Topic模式通信
这与上一篇点对点博客同样采用的是前端接收队列的消息,具体流程如下图
根据路由键来匹配消息队列,成功匹配就将消息加入相应队列。其中符号#表示单词可以任意数量(0、1、多个)、符号*表示任意一个单词必须一次出现。下面我们观察一下演示效果。
根据路由键规则大家可以实现不同情况的消息分发。
Spring boot 的配置类实现了消息队列、交换机,通过路由键将消息队列和交换相互绑定。
/**
* @author zzj
* @date 2021-12-12 06:45:39
*/
@Configuration
public class TopicRabbitConfig {
/**
* 队列
*/
@Bean
public Queue producerTopicTigerQueue()
{
return new Queue("tigerQueue");
}
@Bean
public Queue producerTopicCatQueue()
{
return new Queue("catQueue");
}
@Bean Queue producerTopicDogQueue()
{
return new Queue("dogQueue");
}
/**
* 主题交换机
*/
@Bean
TopicExchange producerTopicExchange() {
return new TopicExchange("producerTopicExchange");
}
/**
* 绑定
*/
@Bean
Binding bindingTigerExchangeQueue() {
return BindingBuilder.bind(producerTopicTigerQueue()).to(producerTopicExchange()).with("#.tiger.#");
}
@Bean
Binding bindingCatExchangeQueue() {
return BindingBuilder.bind(producerTopicCatQueue()).to(producerTopicExchange()).with("cat.#");
}
@Bean
Binding bindingDogExchangeQueue() {
return BindingBuilder.bind(producerTopicDogQueue()).to(producerTopicExchange()).with("*.dog.#");
}
}
控制器实现消息发送接口,接口需要提供参数为路由键和消息内容,接口会根据路由键来匹配到相应的队列加入消息内容。
/**
* @author zzj
* @date 2021-12-10 19:38:14
*/
@RestController
public class SendMessageController {
/**
* 使用RabbitTemplate,这提供了接收/发送等等方法
* 注入对象
*/
@Resource
RabbitTemplate rabbitTemplate;
/**
* 发送主题消息
* @param routingKey 路由键
* @param message 消息内容
* @return 是否成功
*/
@GetMapping("/sendTopicMessage")
public String sendTopicMessage(@RequestParam("routingKey")String routingKey, @RequestParam("message")String message) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String curTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
Map<String,Object> map=new HashMap<>();
map.put("message",message);
map.put("curTime",curTime);
//将消息携带绑定键值:TestDirectRouting 发送到交换机TestDirectExchange
//此处巨坑 要传入前段必须为字符串 其它类型直接报错。。。。。。。。。。。
rabbitTemplate.convertAndSend("producerTopicExchange", routingKey, mapper.writeValueAsString(map));
return "1";
}
}