Springboot集成RabbitMQ之主题模式

主题转发模式

生产者
交换机 topic
消息队列
消息队列
消费者
消费者
  1. 添加依赖
 <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
  1. 添加RabbitMQ属性
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest 
  1. 配置两个队列 topic.a 与 topic.b
 	@Bean
    public Queue top_a(){
        return new Queue("topic.a");
    }

    @Bean
    public Queue top_b(){
        return new Queue("topic.b");
    }
  1. 配置主题交换机 topicExchange
	@Bean
    TopicExchange exchange(){
        return new TopicExchange("topicExchange");
    }
  1. 把队列(topic.a,topic.b)绑定到主题交换机(topicExchange)上,并设置routing key
	@Bean
    Binding bindingExchangeMessage(Queue top_a,TopicExchange exchange){
        // routing key 为 topic.a
        return BindingBuilder.bind(top_a).to(exchange).with("topic.a");     
    }
    @Bean
    Binding bindingExchangeMessages(Queue top_b,TopicExchange exchange){
    	// routing key 为 topic.# , #代表模糊匹配零个或更多的单词
        return BindingBuilder.bind(top_b).to(exchange).with("topic.#");
    } 
  1. 创建两个接收者,绑定创建的两个队列
@Component
@RabbitListener(queues = "topic.a")
public class TopicReceiverA {
    @RabbitHandler
    public void process(String msg){
        System.out.println("接收A:"+msg);
    }
}
@Component
@RabbitListener(queues = "topic.b")
public class TopicReceiverB {
    @RabbitHandler
    public void process(String msg){
        System.out.println("接收B:"+msg);
    }
}
  1. 创建个发送方法用来发送消息
 @Component
public class TopicSender {
    @Autowired
    private AmqpTemplate amqpTemplate;
    public void send(String exchange,String queue,String context){
        this.amqpTemplate.convertAndSend(exchange,queue,context);
    }
}
  1. 发送测试数据 , topic.1 与 topic.b的routing key(topic.#) 匹配 ,所以topic.b接收消息
topicSender.send("topicExchange","topic.1","hello");
//运行结果: 接收B:hello
  1. 发送测试数据 , topic.a 与 topic.b的routing key(topic.#) 和 topic.a的 routing key(topic.a) 都匹配,所以都接收消息
 topicSender.send("topicExchange","topic.a","hello");    
 //运行结果: 接收A:hello 接收B:hello
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值