Sending, Receiving, and Deleting Amazon SQS Messages - AWS SDK for Java 1.x

We announced the upcoming end-of-support for AWS SDK for Java (v1). We recommend that you migrate to AWS SDK for Java v2. For dates, additional details, and information on how to migrate, please refer to the linked announcement.

Sending, Receiving, and Deleting Amazon SQS Messages

This topic describes how to send, receive and delete Amazon SQS messages. Messages are always delivered using an SQS Queue.

Send a Message

Add a single message to an Amazon SQS queue by calling the AmazonSQS client’s sendMessage method. Provide a SendMessageRequest object that contains the queue’s URL, message body, and optional delay value (in seconds).

Imports

import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.SendMessageRequest;

Code

SendMessageRequest send_msg_request = new SendMessageRequest() .withQueueUrl(queueUrl) .withMessageBody("hello world") .withDelaySeconds(5); sqs.sendMessage(send_msg_request);

See the complete example on GitHub.

Send Multiple Messages at Once

You can send more than one message in a single request. To send multiple messages, use the AmazonSQS client’s sendMessageBatch method, which takes a SendMessageBatchRequest containing the queue URL and a list of messages (each one a SendMessageBatchRequestEntry) to send. You can also set an optional delay value per message.

Imports

import com.amazonaws.services.sqs.model.SendMessageBatchRequest; import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry;

Code

SendMessageBatchRequest send_batch_request = new SendMessageBatchRequest() .withQueueUrl(queueUrl) .withEntries( new SendMessageBatchRequestEntry( "msg_1", "Hello from message 1"), new SendMessageBatchRequestEntry( "msg_2", "Hello from message 2") .withDelaySeconds(10)); sqs.sendMessageBatch(send_batch_request);

See the complete example on GitHub.

Receive Messages

Retrieve any messages that are currently in the queue by calling the AmazonSQS client’s receiveMessage method, passing it the queue’s URL. Messages are returned as a list of Message objects.

Imports

import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.AmazonSQSException; import com.amazonaws.services.sqs.model.SendMessageBatchRequest;

Code

List<Message> messages = sqs.receiveMessage(queueUrl).getMessages();

Delete Messages after Receipt

After receiving a message and processing its contents, delete the message from the queue by sending the message’s receipt handle and queue URL to the AmazonSQS client’s deleteMessage method.

Code

for (Message m : messages) { sqs.deleteMessage(queueUrl, m.getReceiptHandle()); }

See the complete example on GitHub.

More Info