The Amazon SDK for Java 1.x has entered maintenance mode as of July 31, 2024,
and will reach end-of-support
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
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
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
More Info
-
How Amazon SQS Queues Work in the Amazon SQS Developer Guide
-
SendMessage
in the Amazon SQS API Reference -
SendMessageBatch
in the Amazon SQS API Reference -
ReceiveMessage
in the Amazon SQS API Reference -
DeleteMessage
in the Amazon SQS API Reference