rabbitmq工作模式详解之主题模式-topic
主题模式是按照路由的匹配规则发送消息,路由模式是根据路由key进行完整的匹配(完全相等才发送消息),这里的通配符模式通俗的来讲就是模糊匹配
注册队列、交换机和绑定关系
package com.gitee.small.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class TopicRabbitConfig {
//绑定键
public final static String DOG = "topic.dog";
public final static String CAT = "topic.cat";
/**
* Queue构造函数参数说明
* new Queue(SMS_QUEUE, true);
* 1. 队列名
* 2. 是否持久化 true:持久化 false:不持久化
*/
@Bean
public Queue firstQueue() {
return new Queue(DOG);
}
@Bean
public Queue secondQueue() {
return new Queue(CAT);
}
@Bean
public TopicExchange exchange() {
return new TopicExchange("topicExchange");
}
/**
* 将firstQueue和topicExchange绑定,而且绑定的键值为topic.dog
* 这样只要是消息携带的路由键是topic.dog,才会分发到该队列
*/
@Bean(name = "binding.dog")
public Binding bindingExchangeMessage() {
return BindingBuilder.bind(firstQueue()).to(exchange()).with(DOG);
}
/**
* 将secondQueue和topicExchange绑定,而且绑定的键值为用上通配路由键规则topic.#
* 这样只要是消息携带的路由键是以topic.开头,都会分发到该队列
*/
@Bean(name = "binding.cat")
public Binding bindingExchangeMessage2() {
return BindingBuilder.bind(secondQueue()).to(exchange()).with("topic.#");
}
}
向topic.dog队列发送消息
rabbitTemplate.convertAndSend("topicExchange", "topic.dog", "路由模式测试-dog");
由于topic.cat队列绑定的路由是topic.#,代表只要是topic.开头的路由都会发送到topic.cat队列上去,所以两个队列都会接收到消息
c.g.small.rabbitmq.TopicRabbitReceiver : cat-收到消息:路由模式测试-dog
c.g.small.rabbitmq.TopicRabbitReceiver : dog-收到消息:路由模式测试-dog
向topic.cat队列发送消息
rabbitTemplate.convertAndSend("topicExchange", "topic.cat", "路由模式测试-cat");
结果示例
c.g.small.rabbitmq.TopicRabbitReceiver : cat-收到消息:路由模式测试-cat