RabbitMQ Java客户端deliveryCallback从未调用过

问题描述 投票:0回答:1

我正在尝试学习如何在RabbitMQ Java API之后使用this tutorial

这是Java代码:

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * Hello world!
 */
public class App {
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) {
        try (Connection connection = createConnection()) {
            try (Channel channel = connection.createChannel()) {
                channel.queueDeclare(QUEUE_NAME, false, false, false, null);
                String message = "Hello World!";
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
                System.out.println(" [x] Sent '" + message + "'");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        try (Connection connection = createConnection()) {
            try (Channel channel = connection.createChannel()) {

                channel.queueDeclare(QUEUE_NAME, false, false, false, null);
                System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
                DeliverCallback deliverCallback = (consumerTag, delivery) -> {
                    String msg = new String(delivery.getBody(), "UTF-8");
                    System.out.println(" [x] Received '" + msg + "'");
                };
                channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> { });

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Connection createConnection() throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("rabbitmq");
        factory.setPassword("rabbitmq");
        factory.setHost("192.168.0.101");
        return factory.newConnection();
    }
}

代码运行得很好,并且消息已被使用,但是问题是deliverCallback从未被调用。我在这里想念什么吗?


RabbitMQ服务器在Docker上运行,具有默认设置。

java rabbitmq
1个回答
0
投票

这是因为您已将Receiver和Sender都合并到一个文件中,结果您的Sender的第一段代码已发送了该消息,但没有人接收它。

我建议您为发件人和接收人准备两个单独的文件,然后并行运行它们。

© www.soinside.com 2019 - 2024. All rights reserved.