Rabbitmq java 客户端 consumer handleDelivery 方法不会被调用



这是一个非常人为的rabbitmq应用程序示例,它在一个主要方法中既是消息的生产者又是消费者。问题是被覆盖的句柄交付方法中的代码永远不会被执行。我使用 Rabbitmq 仪表板,看到队列已满并消耗。并且 handleConsumptionOk 中的行被打印出来。由于我是 rabbitmq 的新手,我想知道我是否做错了什么根本性的事情,或者我只是错误地得到了"当收到这个消费者的基本交付时调用"的想法。

public class RabbitMain {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Connection connection = Utils.getConnection("test");
        String payload = "hello world!";
        try (Channel channel = connection.createChannel()){
            channel.exchangeDeclare("sampleExchange", BuiltinExchangeType.TOPIC, true);
            channel.basicPublish("sampleExchange", "testKey", null, payload.getBytes());
        }
        System.out.println("Consume...");
        try (Channel channel = connection.createChannel()){
            channel.exchangeDeclare("sampleExchange", BuiltinExchangeType.TOPIC, true);
            channel.queueDeclare("testQueue", true, false, false, null);
            channel.queueBind("testQueue", "sampleExchange", "testKey");
            Consumer consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body);
                    System.out.println("Received: " + message);
                }
                @Override
                public void handleConsumeOk(String consumerTag) {
                    System.out.println("handled consume ok");
                }
            };
            Thread.sleep(2000);
            channel.basicConsume("testQueue", true, consumer);
        }
    }
}

在任何队列绑定到消息之前,将消息发布到exchnage。RabbitMQ 将丢弃任何无法路由到队列的消息。

channel.queueDeclare("testQueue", true, false, false, null);
channel.queueBind("testQueue", "sampleExchange", "testKey");

在你打电话给channel.basicPublish之前.

最新更新