RabbitMq主题Topic模式通信(前端接收)

RabbitMq主题Topic模式通信(前端接收),第1张

RabbitMq主题Topic模式通信(前端接收) 4.RabbitMq主题Topic模式通信

​ 这与上一篇点对点博客同样采用的是前端接收队列消息,具体流程如下图


​ 根据路由键来匹配消息队列,成功匹配就将消息加入相应队列。其中符号#表示单词可以任意数量(0、1、多个)、符号*表示任意一个单词必须一次出现。下面我们观察一下演示效果。




​ 根据路由键规则大家可以实现不同情况的消息分发。

​ Spring boot 的配置类实现了消息队列、交换机,通过路由键将消息队列和交换相互绑定。

@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.#");
    }
}

​ 控制器实现消息发送接口,接口需要提供参数为路由键和消息内容,接口会根据路由键来匹配到相应的队列加入消息内容。

@RestController
public class SendMessageController {

    
    @Resource
    RabbitTemplate rabbitTemplate;

    
    @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 map=new HashMap<>();
        map.put("message",message);
        map.put("curTime",curTime);
        //将消息携带绑定键值:TestDirectRouting 发送到交换机TestDirectExchange
        //此处巨坑 要传入前段必须为字符串 其它类型直接报错。。。。。。。。。。。
        rabbitTemplate.convertAndSend("producerTopicExchange", routingKey, mapper.writevalueAsString(map));
        return "1";
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5672966.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存