Async consumer for Amazon sqs

user5118993 picture user5118993 · Aug 26, 2015 · Viewed 16.7k times · Source

I am new to working with queues. I am able to successfully post messages and receive them synchronously However, I am now trying to async now.

The reference links provided by sqs suggests using jmsclient wrapper. And the link also mentions to use it if you already have a code that is integrated to a jms client.

http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/jmsclient.html#samples

But I am starting afresh I referred this example to send and recv messages synchronously.

https://github.com/aws/aws-sdk-java/blob/master/src/samples/AmazonSimpleQueueService/SimpleQueueServiceSample.java

Can I use the same code but implement it with a message listener? Any code examples will be appreciated.

Answer

rbarni picture rbarni · Nov 3, 2016

There's a code sample in the section about Using JMS with Amazon SQS of the Amazon SQS Developer Guide that shows how to asynchronously receive messages using JMS.

First you implement the MessageListener interface:

class MyListener implements MessageListener {

    @Override
    public void onMessage(Message message) {
        try {
            // Cast the received message as TextMessage and print the text to screen.
            if (message != null) {
                System.out.println("Received: " + ((TextMessage) message).getText());
            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

And then you set it as the MessageListener for a MessageConsumer:

// Create a consumer for the 'TestQueue'.
MessageConsumer consumer = session.createConsumer(queue);

// Instantiate and set the message listener for the consumer.
consumer.setMessageListener(new MyListener());

// Start receiving incoming messages.
connection.start();

// Wait for 1 second. The listener onMessage() method will be invoked when a message is received.
Thread.sleep(1000);