Przemek Lach
Przemek Lach

Reputation: 1538

RabbitMQ Java Client Asynchronous Topic Receipt

I have a program that sends and receives messages over an exchange. My program needs to continue execution regardless of whether there is a message for it in the queue. Almost all the tutorials have blocking examples:

while (true) {
     QueueingConsumer.Delivery delivery = consumer.nextDelivery();
     System.out.println("Message: " + new String(delivery.getBody()));
     ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
}

I came across what I understand to be the asynchronous version i.e., the handleDelivery function is called (callback) when a message is available in the queue:

 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);
     }
 });

After reading over the documentation I'm still unsure whether the above code snippet is indeed asynchronous and I still can't figure out how to get the actual message that was sent. Some help please.

Upvotes: 1

Views: 3896

Answers (1)

robthewolf
robthewolf

Reputation: 7624

With out trying the second code snippet I can say that it is possible it does what you want. However it presumably does this but using a thread internally (which will be blocked while waiting for a new message). What I do is stick the while loop in a new Thread so that only that thread is blocked and the rest of your program continues asyncrhonously

Upvotes: 1

Related Questions