rabbitMq 主题模式介绍
主题模式可以简单的理解为可以动态路由,*代表一个单词,#可以代替零个或多个单词,单词最多 255 个字节,通过相关的匹配规则后就会将满足条件的消息放到对应的队列中,每个单词之间要用点隔开
TopicProducer编写
public class TopicProducer {
public static void main(String[] args) throws Exception {
Channel channel = RabbitMqUtils.getChannel();
HashMap<String,String> hashMap=new HashMap<>(16);
hashMap.put("a.orange.b","消费a.orange.b");
hashMap.put("a.b.rabbit","消费a.b.rabbit");
hashMap.put("lazy.orange.b.c","消费lazy.orange.b.c");
for (Map.Entry<String,String> item:hashMap.entrySet()) {
// 发送消息
channel.basicPublish(TopicCustomerOne.EXCHANGE_NAME, item.getKey(), null, item.getValue().getBytes("UTF-8"));
}
System.out.println("消息发送");
}
}
消费者One编写
当前消费者绑定的routingKey是
*.orange.*
一共三个单词
public class TopicCustomerOne {
public static final String EXCHANGE_NAME="topic_log";
public static void main(String[] args) throws Exception{
Channel channel = RabbitMqUtils.getChannel();
// 声明交换机
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
// 临时队列
String queue = channel.queueDeclare().getQueue();
// 绑定交换机
channel.queueBind(queue,EXCHANGE_NAME,"*.orange.*");
System.out.println("消息的接收.......");
DeliverCallback deliverCallback = (String consumerTag, Delivery message) -> {
System.out.println("消息消费: "+new String(message.getBody())+" 绑定的routingKey: "+message.getEnvelope().getRoutingKey());
// 手动应答
channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
};
CancelCallback cancelCallback=(consumerTag)->{
System.out.println("消息消费被中断");
};
// 消费消息
channel.basicConsume(queue,false,deliverCallback,cancelCallback);
}
}
消费者Two编写
当前消费者绑定的routingKey是
*.*.rabbit
和lazy.#
,以rabbit结尾的三个单词或者以lazy开头的单词组
public class TopicCustomerTwo {
public static void main(String[] args) throws Exception{
Channel channel = RabbitMqUtils.getChannel();
// 声明交换机
channel.exchangeDeclare(TopicCustomerOne.EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
// 临时队列
String queue = channel.queueDeclare().getQueue();
// 绑定交换机
channel.queueBind(queue,TopicCustomerOne.EXCHANGE_NAME,"*.*.rabbit");
// 绑定交换机
channel.queueBind(queue,TopicCustomerOne.EXCHANGE_NAME,"lazy.#");
System.out.println("消息的接收.......");
DeliverCallback deliverCallback = (String consumerTag, Delivery message) -> {
System.out.println("消息消费: "+new String(message.getBody())+" 绑定的routingKey: "+message.getEnvelope().getRoutingKey());
// 手动应答
channel.basicAck(message.getEnvelope().getDeliveryTag(),false);
};
CancelCallback cancelCallback=(consumerTag)->{
System.out.println("消息消费被中断");
};
// 消费消息
channel.basicConsume(queue,false,deliverCallback,cancelCallback);
}
}
启动项目
启动消费者发送消息
消费者One接收到的消息是匹配routingKey的
消费者Two接收到的消息是匹配routingKey的