我有一个 RabbitMQ 客户端应用程序,用于侦听特定队列。客户端创建DefaultConsumer的实例并实现handleDelivery方法。这是代码
protected LinkedBlockingQueue<Message> messages = new LinkedBlockingQueue<>();
public void receiveMessages() {
try {
// channel.basicQos(pollCount);
Message message = new Message();
Consumer consumer = new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
throws IOException {
long deliveryTag = envelope.getDeliveryTag();
String response = new String(body, "UTF-8");
if (response != null) {
message.setId(NUID.nextGlobal());
message.setPayload(response);
message.setDeliveryTag(deliveryTag);
messages.add(message);
logger.info("Message received: ", message.getPayload());
}
}
};
logger.debug("**********Channel status: " + channel.isOpen());
channel.basicConsume(queueName, false, consumer);
} catch (Exception e) {
logger.error("Exception while getting messages from Rabbit ", e);
}
}
receiveMessages() 方法每 500 毫秒通过一个线程频繁调用,并将消息放入不同的 List 中进行消费。由于这次对 receiveMessages() 的民意调查,我观察到,当通过兔子控制台查看时,消费者标签不断被创建和增长,如图所示。看到越来越多的消费者标签是否正常?
我终于找到了一个可行的解决方案。 正如卢克·巴肯(Luke Bakken)强调的那样,不需要进行民意调查。我现在只打过一次
receiveMesssages()
。此后,当消息发布到队列中时,我的消费者就会收到回调。
protected LinkedBlockingQueue<Message> messages = new LinkedBlockingQueue<>();
public void receiveMessages() {
try {
Message message = new Message();
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
long deliveryTag = delivery.getEnvelope().getDeliveryTag();
String response = new String(delivery.getBody(), "UTF-8");
if (response != null) {
message.setId(NUID.nextGlobal());
message.setPayload(response);
message.setDeliveryTag(deliveryTag);
messages.add(message);
logger.info("Message received: ", message.getPayload());
};
channel.basicConsume(queueName, false, deliverCallback, consumerTag -> { });
} catch (Exception e) {
logger.error("Exception while getting messages from Rabbit ", e);
}
}
Rabbit 控制台现在在绑定队列下仅显示 1 个消耗标签条目。
看到越来越多的消费者标签正常吗?
不,您的代码有错误。您需要只使用长期运行的消费者,或者在使用完毕后必须取消您的消费者。
我看不出有任何需要“轮询”
receiveMessages
- 只需让它自行运行,它就会按照您的预期将消息添加到您的同步队列中。
public NotificationConsumerService(ConnectionFactory connectionFactory, String host, Logger logger) {
this.connectionFactory = connectionFactory;
this.host = host;
this.logger = logger;
}
public void consumeSliceChangeNotification() {
connectionFactory.setHost(this.host);
try (Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel()) {
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String message = new String(delivery.getBody(), "UTF-8");
JSONObject obj = new JSONObject(message);
String namespace = obj.getString("namespace");
logger.info("The latest change notification on the " + namespace +" is available");
};
channel.basicConsume(QUEUE_NAME, true,deliverCallback, consumerTag -> { } );
}
catch (IOException | TimeoutException e) {
e.printStackTrace();
}
}