我有一个通过交换机发送和接收消息的程序。无论队列中是否有消息,我的程序都需要继续执行。几乎所有教程都有阻塞示例:
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
System.out.println("Message: " + new String(delivery.getBody()));
ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}
我遇到了我理解的异步版本,即当队列中有消息时调用(回调)handleDelivery 函数:
boolean autoAck = false;
channel.basicConsume(queueName, autoAck, "myConsumerTag",
new DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag,
Envelope envelope,
AMQP.BasicProperties properties,
byte[] body)
throws IOException
{
String routingKey = envelope.getRoutingKey();
String contentType = properties.contentType;
long deliveryTag = envelope.getDeliveryTag();
// (process the message components here ...)
channel.basicAck(deliveryTag, false);
}
});
在阅读完文档后,我仍然不确定上面的代码片段是否确实是异步的,我仍然无法弄清楚如何获取发送的实际消息。请帮忙。