I have a problem with RabbitMQ consumer. Actually i have a single consumer geting messages from three queues. The problem is that i need to get a multiple messages from each of them, but my consumer gets only one per queue and ends getting. I would be grateful if someone could help me solve this problem.
Consumer code below
for (int i = 0; i < queueNames.size(); i++) {
Channel channel = connection.createChannel();
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueNames.get(i).toString(), true, consumer_tag, consumer);
flag = true;
while (flag) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String routingKey = delivery.getEnvelope().getRoutingKey();
System.out.println(routingKey);
String message = new String(delivery.getBody(), "UTF-8");
flag = false;
}
}
where queueNames is a list containing names of my queues (in number of 3).
You need to subscribe to the queue, a consumer will only consume 1 message the way you defined it
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.getContentType();
long deliveryTag = envelope.getDeliveryTag();
// (process the message components here ...)
channel.basicAck(deliveryTag, false);
}
});
More info here: https://www.rabbitmq.com/api-guide.html
OK i solve the problem this way:
boolean flag;
System.out.println("Rozmiar queue " + queueNames.size());
for (int i = 0; i < queueNames.size(); i++) {
Channel channel = connection.createChannel();
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueNames.get(i).toString(), true, consumer_tag, consumer);
flag = true;
while (flag) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery(timeout);
if (delivery == null) {
flag = false;
} else {
String message = new String(delivery.getBody(), "UTF-8");
System.out.println(" [x] Message Received '" + message + "'");
}
}
}
I hope this solution could help someone in future :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.