AWS code-library documentation change
Summary
Added detailed Java code examples demonstrating batch message operations with Amazon SQS, including explicit batch handling (SendRecvBatch.java) and automatic batching using SqsAsyncBatchManager (SimpleProducerConsumer.java), along with explanations of batching approaches and API documentation links
Security assessment
The changes focus on operational efficiency and code structure improvements for batch message processing. While they demonstrate error handling for failed operations, there is no evidence of addressing security vulnerabilities or documenting specific security features. The examples primarily cover performance optimization through batching rather than security controls.
Diff
diff --git a/code-library/latest/ug/sqs_example_sqs_Scenario_SendReceiveBatch_section.md b/code-library/latest/ug/sqs_example_sqs_Scenario_SendReceiveBatch_section.md index 0d8df3330..6712108c8 100644 --- a//code-library/latest/ug/sqs_example_sqs_Scenario_SendReceiveBatch_section.md +++ b//code-library/latest/ug/sqs_example_sqs_Scenario_SendReceiveBatch_section.md @@ -9 +9 @@ There are more AWS SDK examples available in the [AWS Doc SDK Examples](https:// -The following code example shows how to: +The following code examples show how to: @@ -21,0 +22,964 @@ The following code example shows how to: +Java + + +**SDK for Java 2.x** + + +###### Note + +There's more on GitHub. Find the complete example and learn how to set up and run in the [AWS Code Examples Repository](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sqs#code-examples). + +You can handle batch message operations with Amazon SQS using two different approaches with the AWS SDK for Java 2.x: + +**SendRecvBatch.java** uses explicit batch operations. You manually create message batches and call `sendMessageBatch()` and `deleteMessageBatch()` directly. You also handle batch responses, including any failed messages. This approach gives you full control over batch sizing and error handling. However, it requires more code to manage the batching logic. + +**SimpleProducerConsumer.java** uses the high-level `SqsAsyncBatchManager` library for automatic request batching. You make individual `sendMessage()` and `deleteMessage()` calls with the same method signatures as the standard client. The SDK automatically buffers these calls and sends them as batch operations. This approach requires minimal code changes while providing batching performance benefits. + +Use explicit batching when you need fine-grained control over batch composition and error handling. Use automatic batching when you want to optimize performance with minimal code changes. + +SendRecvBatch.java - Uses explicit batch operations with messages. + + + import org.slf4j.Logger; + import org.slf4j.LoggerFactory; + import software.amazon.awssdk.services.sqs.SqsClient; + import software.amazon.awssdk.services.sqs.model.BatchResultErrorEntry; + import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; + import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequest; + import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchRequestEntry; + import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchResponse; + import software.amazon.awssdk.services.sqs.model.DeleteMessageBatchResultEntry; + import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest; + import software.amazon.awssdk.services.sqs.model.Message; + import software.amazon.awssdk.services.sqs.model.MessageAttributeValue; + import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; + import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequest; + import software.amazon.awssdk.services.sqs.model.SendMessageBatchRequestEntry; + import software.amazon.awssdk.services.sqs.model.SendMessageBatchResponse; + import software.amazon.awssdk.services.sqs.model.SendMessageBatchResultEntry; + import software.amazon.awssdk.services.sqs.model.SqsException; + + import java.io.BufferedReader; + import java.io.IOException; + import java.io.InputStream; + import java.io.InputStreamReader; + import java.util.ArrayList; + import java.util.HashMap; + import java.util.List; + import java.util.Map; + + + /** + * Before running this Java V2 code example, set up your development + * environment, including your credentials. + * + * For more information, see the following documentation topic: + * + * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html + */ + + /** + * This code demonstrates basic message operations in Amazon Simple Queue Service (Amazon SQS). + */ + + public class SendRecvBatch { + private static final Logger LOGGER = LoggerFactory.getLogger(SendRecvBatch.class); + private static final SqsClient sqsClient = SqsClient.create(); + + + public static void main(String[] args) { + usageDemo(); + } + /** + * Send a batch of messages in a single request to an SQS queue. + * This request may return overall success even when some messages were not sent. + * The caller must inspect the Successful and Failed lists in the response and + * resend any failed messages. + * + * @param queueUrl The URL of the queue to receive the messages. + * @param messages The messages to send to the queue. Each message contains a body and attributes. + * @return The response from SQS that contains the list of successful and failed messages. + */ + public static SendMessageBatchResponse sendMessages( + String queueUrl, List<MessageEntry> messages) { + + try { + List<SendMessageBatchRequestEntry> entries = new ArrayList<>(); + + for (int i = 0; i < messages.size(); i++) { + MessageEntry message = messages.get(i); + entries.add(SendMessageBatchRequestEntry.builder() + .id(String.valueOf(i)) + .messageBody(message.getBody()) + .messageAttributes(message.getAttributes()) + .build()); + } + + SendMessageBatchRequest sendBatchRequest = SendMessageBatchRequest.builder() + .queueUrl(queueUrl) + .entries(entries) + .build(); + + SendMessageBatchResponse response = sqsClient.sendMessageBatch(sendBatchRequest); + + if (!response.successful().isEmpty()) { + for (SendMessageBatchResultEntry resultEntry : response.successful()) { + LOGGER.info("Message sent: {}: {}", resultEntry.messageId(), + messages.get(Integer.parseInt(resultEntry.id())).getBody()); + } + } + + if (!response.failed().isEmpty()) { + for (BatchResultErrorEntry errorEntry : response.failed()) { + LOGGER.warn("Failed to send: {}: {}", errorEntry.id(), + messages.get(Integer.parseInt(errorEntry.id())).getBody()); + } + } + + return response; + + } catch (SqsException e) { + LOGGER.error("Send messages failed to queue: {}", queueUrl, e); + throw e; + } + } + + /** + * Receive a batch of messages in a single request from an SQS queue. + * + * @param queueUrl The URL of the queue from which to receive messages. + * @param maxNumber The maximum number of messages to receive (capped at 10 by SQS). + * The actual number of messages received might be less. + * @param waitTime The maximum time to wait (in seconds) before returning. When + * this number is greater than zero, long polling is used. This + * can result in reduced costs and fewer false empty responses. + * @return The list of Message objects received. These each contain the body + * of the message and metadata and custom attributes. + */ + public static List<Message> receiveMessages(String queueUrl, int maxNumber, int waitTime) { + try { + ReceiveMessageRequest receiveRequest = ReceiveMessageRequest.builder() + .queueUrl(queueUrl) + .maxNumberOfMessages(maxNumber) + .waitTimeSeconds(waitTime) + .messageAttributeNames("All") + .build(); + + List<Message> messages = sqsClient.receiveMessage(receiveRequest).messages(); + + for (Message message : messages) { + LOGGER.info("Received message: {}: {}", message.messageId(), message.body()); + } + + return messages; + + } catch (SqsException e) { + LOGGER.error("Couldn't receive messages from queue: {}", queueUrl, e); + throw e; + } + } + + /** + * Delete a batch of messages from a queue in a single request. + * + * @param queueUrl The URL of the queue from which to delete the messages. + * @param messages The list of messages to delete. + * @return The response from SQS that contains the list of successful and failed + * message deletions. + */ + public static DeleteMessageBatchResponse deleteMessages(String queueUrl, List<Message> messages) { + try { + List<DeleteMessageBatchRequestEntry> entries = new ArrayList<>(); + + for (int i = 0; i < messages.size(); i++) { + entries.add(DeleteMessageBatchRequestEntry.builder() + .id(String.valueOf(i)) + .receiptHandle(messages.get(i).receiptHandle()) + .build()); + } + + DeleteMessageBatchRequest deleteRequest = DeleteMessageBatchRequest.builder() + .queueUrl(queueUrl) + .entries(entries) + .build(); + + DeleteMessageBatchResponse response = sqsClient.deleteMessageBatch(deleteRequest); + + if (!response.successful().isEmpty()) { + for (DeleteMessageBatchResultEntry resultEntry : response.successful()) { + LOGGER.info("Deleted {}", messages.get(Integer.parseInt(resultEntry.id())).receiptHandle()); + } + } +