Menu
AWS SDK for Java
Developer Guide

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

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

Code

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

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

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

Code

Copy
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 sample.

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

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

Code

Copy
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

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

See the complete sample.

More Info