1. poll方式接受消息
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, true, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String message = new String(delivery.getBody());
String routingKey = delivery.getEnvelope().getRoutingKey();
System.out.println(" [x] Received '" + routingKey + "':'" + message + "'");
}
}
2. 订阅或者事件驱动方式接受消息
Receiving messages by subscription
import com.rabbitmq.client.Consumer; import com.rabbitmq.client.DefaultConsumer;
The most efficient way to receive messages is to set up a subscription using the Consumer interface. The messages will then be delivered automatically as they arrive, rather than having to be explicitly requested.
When calling the API methods relating to Consumers, individual subscriptions are always referred to by their consumer tags, which can be either client- or server-generated as explained in