Version: Next
Routing Topic 模式
类似
动态路由
Topic类型的Exchange与Direct相比,都是可以根据RoutingKey把消息路由到不同的队列Topic类型的Exchange可以让队列在绑定RoutingKey的时候使用通配符- 这种模式
RoutingKey一般都是一个或者多个单次组成,多个单词之间用.分割,例如item.insert
*:匹配1个词#:匹配1个或多个词
a.*:只能匹配a.b、a.c之类的a.#:能匹配a.b.c、a.c.b、a.b.c.d等

生产者实现
public class ProviderTopic {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMqUtils.getConnection();
Channel channel = connection.createChannel();
String exchangeName = "topics";
// 声明交换机类型为 TOPIC
channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC);
// 发送消息
String routingKey = "user.save.1";
channel.basicPublish(exchangeName,
routingKey,
null,
("topic 模式消息 | Routing Key -> [" + routingKey + "]").getBytes());
RabbitMqUtils.closeConnectionAndChannel(connection, channel);
}
}
消费者实现
- 消费者 1
- 消费者 2
消费者1
public class ConsumerTopic1 {
public static void main(String[] args) throws IOException {
Connection connection = RabbitMqUtils.getConnection();
Channel channel = connection.createChannel();
String exchangeName = "topics";
channel.exchangeDeclare(exchangeName, BuiltinExchangeType.TOPIC);
String queue = channel.queueDeclare().getQueue();
String routingKey = "user.*"; // 通配,2个单次组成,第一个单次必须是 user
channel.queueBind(queue, exchangeName, routingKey);
channel.basicConsume(queue, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println("消费者1 通配规则[" + routingKey + "]-> " + new String(body));
}
});
}
}
测试
消费者1
消费者1 通配规则[user.#]-> topic 模式消息 | Routing Key -> [user.save.1]
消费者2
不消费