gpt4 book ai didi

java - RabbitMQ 消费者仅消费一条消息,确认该消息并停止监听

转载 作者:行者123 更新时间:2023-11-30 02:52:06 24 4
gpt4 key购买 nike

我正在查看 Java 中的 RabbitMQ HelloWorld 示例 https://www.rabbitmq.com/tutorials/tutorial-one-java.html

制作人:

        ConnectionFactory factory = new ConnectionFactory();
factory.setHost(host);
factory.setPort(Integer.parseInt(port));
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

channel.queueDeclare(queueName, false, false, false, null);

channel.basicPublish("", queueName, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");

channel.close();
connection.close();

消费者:

        ConnectionFactory factory = new ConnectionFactory();
factory.setHost(host);
factory.setPort(Integer.parseInt(port));
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

channel.queueDeclare(queueName, false, false, false, null);
System.out.println(" [*] Waiting for messages.");

QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, true, consumer);

QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);
if (delivery != null) {
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
} else {
System.out.println(" [x] No messages received");
}

有没有办法编写我的消费者,使其只接收消息并停止监听?

最佳答案

将消费者代码修改为以下内容。这对我有用。

        ConnectionFactory factory = new ConnectionFactory();
factory.setHost(host);
factory.setPort(Integer.parseInt(port));
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

channel.queueDeclare(queueName, false, false, false, null);
System.out.println(" [*] Waiting for messages.");

QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, true, consumer);

QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);
while (delivery != null) {
String message = new String(delivery.getBody());
System.out.println(" [x] Received '" + message + "'");
delivery = consumer.nextDelivery(1000);
}
channel.close();
connection.close();

关于java - RabbitMQ 消费者仅消费一条消息,确认该消息并停止监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38314460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com