1.模型图
实现过程:该模式与Routing模式实现的功能是一样的。但是相对于Routing模式而言,它的routingKey支持通配符的模式去匹配,比Routing模式更加的灵活。Routing模式匹配多个路由键需要重复写大量相同代码,使用Topics模式的通配符只需要一次即可。该模式建议路由键的多个单词以.分割
*:匹配一个字符
#:匹配0到多个字符
2.代码实现
生产者
public class Send {
public static void main(String[] args) throws IOException {
// 获取连接
Connection connection = MqUtil.getConnection();
// 创建通道
Channel channel = connection.createChannel();
// 声明交换机
/*
* 参数1:交换机名称
* 参数2:交换机类型,共四个direct,fanout,topic,headers,路由模式下是topic
* 参数3:是否持久化
* 参数4:是否自动删除
* 参数5:是否内置,true表示是内置的交换器, 客户端程序无法直接发送消息到这个交换器中, 只能通过交换器路由到交换器这个方式
* 参数6; 路由器其他 参数的设置,参考queueDeclare参数详解
* */
channel.exchangeDeclare("topicTest", BuiltinExchangeType.TOPIC,true,false,false,null);
// 发布消息
String routingKey = "user.test2";
channel.basicPublish("topicTest",routingKey,null,"topic test".getBytes());
// 关闭资源
MqUtil.close(channel,connection);
}
}
消费者1
public class Recv1 {
public static void main(String[] args) throws IOException {
Connection connection = MqUtil.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("topicTest", BuiltinExchangeType.TOPIC,true,false,false,null);
// 获取一个临时队列:该队列特点:不持久化,排他,自动删除,也可以自己声明一个
String queueName = channel.queueDeclare().getQueue();
// 绑定队列
/*
* 参数1:队列名称
* 参数2:交换机名称
* 参数3:路由键
* 参数4:额外参数,参考queueDeclare参数详解
* */
channel.queueBind(queueName,"topicTest","user.#",null);
channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(new String(body));
}
});
}
}
消费者2
public class Recv2 {
public static void main(String[] args) throws IOException {
Connection connection = MqUtil.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("topicTest", BuiltinExchangeType.TOPIC,true,false,false,null);
// 获取一个临时队列:该队列特点:不持久化,排他,自动删除,也可以自己声明一个
String queueName = channel.queueDeclare().getQueue();
// 绑定队列
/*
* 参数1:队列名称
* 参数2:交换机名称
* 参数3:路由键
* 参数4:额外参数,参考queueDeclare参数详解
* */
channel.queueBind(queueName,"topicTest","#.product.#",null);
channel.basicConsume(queueName, true, new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
System.out.println(new String(body));
}
});
}
}