rabbitmq工作模式(三)Topics通配符模式

RabbitMQ的工作模式包括了:简单模式、工作队列模式、发布订阅模式、路由模式、TOPICS(通配符模式)以及RPC。本文主要介绍topics模式。

 如图,一个交换机可以绑定一个或多个队列,一个队列可以设定一个或多个带通配符的routingkey。生产者将消息发送给交换机,交换机根据routingKey的值来对队列进行匹配,匹配时采用通配符模式,匹配成功将消息发送到相关队列。

springboot整合rabbitmq实现topics模式

创建生产者

(1)创建RabbitConfig类文件

@Configuration
public class RabbitConfig {
    @Bean("queueA")
    public Queue createQueueA(){
        return new Queue("queueA");
    }
    @Bean("queueB")
    public Queue createQueueB(){
        return new Queue("queueB");
    }

    @Bean("queueAll")
    public Queue createQueueAll(){
        return new Queue("queueAll");
    }


    @Bean("topicExchange")
    public TopicExchange createTopicExchange(){
        return new TopicExchange("topicExchange");
    }
    @Bean
    public Binding BindQueueA(@Qualifier("queueA")Queue queueA,@Qualifier("topicExchange") TopicExchange topicExchange ){
        return BindingBuilder.bind(queueA).to(topicExchange).with("queue.A");
    }
    @Bean
    public Binding BindQueueB(@Qualifier("queueB")Queue queueB,@Qualifier("topicExchange") TopicExchange topicExchange ){
        return BindingBuilder.bind(queueB).to(topicExchange).with("queue.B");
    }
    @Bean
    public Binding BindQueueAll(@Qualifier("queueAll")Queue queueAll,@Qualifier("topicExchange") TopicExchange topicExchange){
        return BindingBuilder.bind(queueAll).to(topicExchange).with("queue.*");
    }
}

(2)创建测试类,向队列发送信息

@SpringBootTest
class ProducerApplicationTests {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Test
    void contextLoads() {
        rabbitTemplate.convertAndSend("topicExchange","queue.A","向QueueA中发送信息queue.A");
        rabbitTemplate.convertAndSend("topicExchange","queue.B","向QueueB中发送信息queue.B");
    }
}

创建消费者

public class ConsumerA {
    @RabbitListener(queues = "queueA")
    @RabbitHandler
    public void receiveMessageA(String data){
        System.out.println("queueA:"+data);
    }


    @RabbitListener(queues = "queueB")
    @RabbitHandler
    public void receiveMessageB(String data){
        System.out.println("queueB:"+data);
    }
}

实验结果

启动生产者,从rabbitmq管理界面查看queue信息,分别向queueA、queueB和queueAll中添加消息。

启动消费者,信息消费成功。

原文地址:https://www.cnblogs.com/menbo/p/13458265.html