在使用RabbitMQ的topic模式时,发现不管怎么改变路由键的范围,消费者都能获取消息,先看一下代码
生产者:
public class Send {
private static final String EXCHANGE_NAME = "topic_exchange";
private static final String ROUTE_KEY = "red.apple.ss";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
String msg = "topic exchange";
channel.basicPublish(EXCHANGE_NAME, ROUTE_KEY, null, msg.getBytes());
System.out.println(" [x] Sent '" + msg + "'");
channel.close();
connection.close();
}
}
消费者
public class Recv1 {
private static final String EXCHANGE_NAME = "topic_exchange";
private static final String QUEUE_NAME = "apple_queue";
public static void main(String[] args) throws IOException, TimeoutException {
Connection connection = ConnectionUtils.getConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, "*.apple.*");
DefaultConsumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
String msg = new String(body);
System.out.println(envelope.getRoutingKey());
System.out.println(" [消费者1] received : " + msg + "!");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
此时生产者绑定的路由键为red.apple.ss,而消费者绑定的路由键为*.apple.*,此时消费者能获取到消息。
image.png
到这里都很正常,但是我把消费者绑定的路由键改为*.banana.*后,消费者居然还能获取到消息
image.png
这就很不科学,后来发现,其实导致这个问题的原因就在于多次在代码里改变了routingkey的范围,每次更改都会在RabbitMQ中添加范围,但代码修改后,该范围仍然存在。虽然我后来把路由键的范围改为了*.banana.*,但 *.apple.* 的范围依旧存在,也就是说同时绑定了两个路由键。所以我们只要去RabbitMQ控制页面Exchange里bindings里的绑定删掉,重新运行即可。
image.png
果然这里绑定了两个路由键,删掉范围为*.apple.*的路由键,重新运行,就接收不到消息了,问题解决。
网友评论