id
stringlengths 8
78
| source
stringclasses 743
values | chunk_id
int64 1
5.05k
| text
stringlengths 593
49.7k
|
---|---|---|---|
sqs-dg-030
|
sqs-dg.pdf
| 30 |
allocation tags To organize and identify your Amazon SQS queues for cost allocation, you can add metadata tags that identify a queue's purpose, owner, or environment. This is especially useful when you have many queues. To configure tags using the Amazon SQS console, see the section called “Configuring tags for a queue” You can use cost allocation tags to organize your AWS bill to reflect your own cost structure. To do this, sign up to get your AWS account bill to include tag keys and values. For more information, see Setting Up a Monthly Cost Allocation Report in the AWS Billing User Guide. List queue pagination 78 Amazon Simple Queue Service Developer Guide Each tag consists of a key-value pair that you define. For example, you can easily identify your production and testing queues if you tag your queues as follows: Key QueueType QueueType Value Production Testing Queue MyQueueA MyQueueB Note When you use queue tags, keep the following guidelines in mind: • We don't recommend adding more than 50 tags to a queue. Tagging supports Unicode characters in UTF-8. • Tags don't have any semantic meaning. Amazon SQS interprets tags as character strings. • Tags are case-sensitive. • A new tag with a key identical to that of an existing tag overwrites the existing tag. • Tagging actions are limited to 30 TPS per AWS account. If your application requires a higher throughput, submit a request. For a full list of tag restrictions, see Amazon SQS standard queue quotas. Amazon SQS short and long polling Amazon SQS offers short and long polling options for receiving messages from a queue. Consider your application's requirements for responsiveness and cost efficiency when choosing between these two polling options: • Short polling (default) – The ReceiveMessage request queries a subset of servers (based on a weighted random distribution) to find available messages and sends an immediate response, even if no messages are found. • Long polling – ReceiveMessage queries all servers for messages, sending a response once at least one message is available, up to the specified maximum. An empty response is sent only Short and long polling 79 Amazon Simple Queue Service Developer Guide if the polling wait time expires. This option can reduce the number of empty responses and potentially lower costs. The following sections explain the details of short polling and long polling. Consuming messages using short polling When you consume messages from a queue (FIFO or standard) using short polling, Amazon SQS samples a subset of its servers (based on a weighted random distribution) and returns messages from only those servers. Thus, a particular ReceiveMessage request might not return all of your messages. However, if you have fewer than 1,000 messages in your queue, a subsequent request will return your messages. If you keep consuming from your queues, Amazon SQS samples all of its servers, and you receive all of your messages. The following diagram shows the short-polling behavior of messages returned from a standard queue after one of your system components makes a receive request. Amazon SQS samples several of its servers (in gray) and returns messages A, C, D, and B from these servers. Message E isn't returned for this request, but is returned for a subsequent request. Consuming messages using long polling When the wait time for the ReceiveMessage API action is greater than 0, long polling is in effect. The maximum long polling wait time is 20 seconds. Long polling helps reduce the cost of using Amazon SQS by eliminating the number of empty responses (when there are no messages Consuming messages using short polling 80 Amazon Simple Queue Service Developer Guide available for a ReceiveMessage request) and false empty responses (when messages are available but aren't included in a response). For information about enabling long polling for a new or existing queue using the Amazon SQS console, see the Configuring queue parameters using the Amazon SQS console. For best practices, see Setting-up long polling in Amazon SQS. Long polling offers the following benefits: • Reduce empty responses by allowing Amazon SQS to wait until a message is available in a queue before sending a response. Unless the connection times out, the response to the ReceiveMessage request contains at least one of the available messages, up to the maximum number of messages specified in the ReceiveMessage action. In rare cases, you might receive empty responses even when a queue still contains messages, especially if you specify a low value for the ReceiveMessageWaitTimeSeconds parameter. • Reduce false empty responses by querying all—rather than a subset of—Amazon SQS servers. • Return messages as soon as they become available. For information about how to confirm that a queue is empty, see Confirming that an Amazon SQS queue is empty. Differences between long and short polling Short polling occurs
|
sqs-dg-031
|
sqs-dg.pdf
| 31 |
ReceiveMessage request contains at least one of the available messages, up to the maximum number of messages specified in the ReceiveMessage action. In rare cases, you might receive empty responses even when a queue still contains messages, especially if you specify a low value for the ReceiveMessageWaitTimeSeconds parameter. • Reduce false empty responses by querying all—rather than a subset of—Amazon SQS servers. • Return messages as soon as they become available. For information about how to confirm that a queue is empty, see Confirming that an Amazon SQS queue is empty. Differences between long and short polling Short polling occurs when the WaitTimeSeconds parameter of a ReceiveMessage request is set to 0 in one of two ways: • The ReceiveMessage call sets WaitTimeSeconds to 0. • The ReceiveMessage call doesn’t set WaitTimeSeconds, but the queue attribute ReceiveMessageWaitTimeSeconds is set to 0. Amazon SQS visibility timeout When you receive a message from an Amazon SQS queue, it remains in the queue but becomes temporarily invisible to other consumers. This invisibility is controlled by the visibility timeout, which ensures that other consumers cannot process the same message while you are working on it. Amazon SQS offers two options for deleting messages after processing: • Manual deletion – You explicitly delete messages using the DeleteMessage action. Differences between long and short polling 81 Amazon Simple Queue Service Developer Guide • Automatic deletion – Supported in certain AWS SDKs, messages are automatically deleted upon successful processing, simplifying workflows. Visibility timeout use cases Manage long-running tasks – Use the visibility timeout to handle tasks that require extended processing times. Set an appropriate visibility timeout for messages that require extended processing time. This ensures that other consumers don't pick up the same message while it's being processed, preventing duplicate work and maintaining system efficiency. Implement retry mechanisms – Extend the visibility timeout programmatically for tasks that fail to complete within the initial timeout. If a task fails to complete within the initial visibility timeout, you can extend the timeout programmatically. This allows your system to retry processing the message without it becoming visible to other consumers, improving fault tolerance and reliability. Combine with Dead-Letter Queues (DLQs) to manage persistent failures. Coordinate distributed systems – Use SQS visibility timeout to coordinate tasks across distributed systems. Set visibility timeouts that align with your expected processing times for different components. This helps maintain consistency and prevents race conditions in complex, distributed architectures. Optimize resource utilization – Adjust SQS visibility timeouts to optimize resource utilization in your application. By setting appropriate timeouts, you can ensure that messages are processed efficiently without tying up resources unnecessarily. This leads to better overall system performance and cost-effectiveness. Visibility timeout use cases 82 Amazon Simple Queue Service Developer Guide Setting and adjusting the visibility timeout The visibility timeout starts as soon as a message is delivered to you. During this period, you're expected to process and delete the message. If you don't delete it before the timeout expires, the message becomes visible again in the queue and can be retrieved by another consumer. The default visibility timeout for a queue is 30 seconds, but you can adjust this to match the time your application needs to process and delete a message. You can also set a specific visibility timeout for individual messages without changing the queue's overall setting. Use the ChangeMessageVisibility action to programmatically extend or shorten the timeout as needed. In flight messages and quotas In Amazon SQS, in-flight messages are messages that have been received by a consumer but not yet deleted. For standard queues, there's a limit of approximately 120,000 in-flight messages, depending on queue traffic and message backlog. If you reach this limit, Amazon SQS returns an OverLimit error, indicating that no additional messages can be received until some in-flight messages are deleted. For FIFO queues, limits depend on active message groups. • When using short polling – If this limit is reached while using short polling, Amazon SQS will return an OverLimit error, indicating that no additional messages can be received until some in-flight messages are deleted. • When using long polling – If you are using long polling, Amazon SQS does not return an error when the in-flight message limit is reached. Instead, it will not return any new messages until the number of in-flight messages drops below the limit. To manage in-flight messages effectively: 1. Prompt deletion – Delete messages (manually or automatically) after processing to reduce the in-flight count. 2. Monitor with CloudWatch – Set alarms for high in-flight counts to prevent reaching the limit. 3. Distribute load – If you're processing a high volume of messages, use additional queues or consumers to balance load and avoid bottlenecks. 4. Request a quota increase – Submit a request to AWS Support if higher limits are required. Setting
|
sqs-dg-032
|
sqs-dg.pdf
| 32 |
message limit is reached. Instead, it will not return any new messages until the number of in-flight messages drops below the limit. To manage in-flight messages effectively: 1. Prompt deletion – Delete messages (manually or automatically) after processing to reduce the in-flight count. 2. Monitor with CloudWatch – Set alarms for high in-flight counts to prevent reaching the limit. 3. Distribute load – If you're processing a high volume of messages, use additional queues or consumers to balance load and avoid bottlenecks. 4. Request a quota increase – Submit a request to AWS Support if higher limits are required. Setting and adjusting the visibility timeout 83 Amazon Simple Queue Service Developer Guide Understanding visibility timeout in standard and FIFO queues In both standard and FIFO (First-In-First-Out) queues, the visibility timeout helps prevent multiple consumers from processing the same message simultaneously. However, due to the at-least-once delivery model of Amazon SQS, there's no absolute guarantee that a message won't be delivered more than once during the visibility timeout period. • Standard queues – The visibility timeout in standard queues prevents multiple consumers from processing the same message at the same time. However, because of the at-least-once delivery model, Amazon SQS doesn't guarantee that a message won’t be delivered more than once within the visibility timeout period. • FIFO queues – For FIFO queues, messages with the same message group ID are processed in a strict sequence. When a message with a message group ID is in-flight, subsequent messages in that group are not made available until the in-flight message is either deleted or the visibility timeout expires. However, this doesn’t "lock" the group indefinitely– each message is processed in sequence, and only when each message is deleted or becomes visible again will the next message in that group be available to consumers. This approach ensures ordered processing within the group without unnecessarily locking the group from delivering messages. Handling failures If you don't process and delete a message before the visibility timeout expires—due to application errors, crashes, or connectivity problems—the message becomes visible again in the queue. It can then be retrieved by the same or a different consumer for another processing attempt. This ensures that messages aren't lost even if the initial processing fails. However, setting the visibility timeout too high can delay the reappearance of unprocessed messages, potentially slowing down retries. It's crucial to set an appropriate visibility timeout based on the expected processing time for timely message handling. Changing and terminating visibility timeout You can change or terminate the visibility timeout using the ChangeMessageVisibility action: • Changing the timeout – Adjust the visibility timeout dynamically using ChangeMessageVisibility. This allows you to extend or reduce timeout durations to match processing needs. Understanding visibility timeout in standard and FIFO queues 84 Amazon Simple Queue Service Developer Guide • Terminating the timeout – If you decide not to process a received message, terminate its visibility timeout by setting the VisibilityTimeout to 0 seconds through the ChangeMessageVisibility action. This immediately makes the message available for other consumers to process. Best practices Use the following best practices for managing visibility timeouts in Amazon SQS, including setting, adjusting, and extending timeouts, as well as handling unprocessed messages using Dead-Letter Queues (DLQs). • Setting and adjusting the timeout. Start by setting the visibility timeout to match the maximum time your application typically needs to process and delete a message. If you're unsure about the exact processing time, begin with a shorter timeout (for example, 2 minutes) and extend it as necessary. Implement a heartbeat mechanism to periodically extend the visibility timeout, ensuring the message remains invisible until processing is complete. This minimizes delays in reprocessing unhandled messages and prevents premature visibility. • Extending the timeout and handling the 12-Hour limit. If your processing time varies or may exceed the initially set timeout, use the ChangeMessageVisibility action to extend the visibility timeout while processing the message. Keep in mind that the visibility timeout has a maximum limit of 12 hours from when the message is first received. Extending the timeout doesn't reset this 12-hour limit. If your processing requires more time than this limit, consider using AWS Step Functions or breaking the task into smaller steps. • Handling unprocessed messages. To manage messages that fail multiple processing attempts, configure a Dead-Letter Queue (DLQ). This ensures that messages that can't be processed after several retries are captured separately for further analysis or handling, preventing them from repeatedly circulating in the main queue. Amazon SQS delay queues Delay queues let you postpone the delivery of new messages to consumers for a number of seconds, for example, when your consumer application needs additional time to process messages. If you create a delay queue, any messages that you send to the queue remain invisible to consumers for the duration of
|
sqs-dg-033
|
sqs-dg.pdf
| 33 |
• Handling unprocessed messages. To manage messages that fail multiple processing attempts, configure a Dead-Letter Queue (DLQ). This ensures that messages that can't be processed after several retries are captured separately for further analysis or handling, preventing them from repeatedly circulating in the main queue. Amazon SQS delay queues Delay queues let you postpone the delivery of new messages to consumers for a number of seconds, for example, when your consumer application needs additional time to process messages. If you create a delay queue, any messages that you send to the queue remain invisible to consumers for the duration of the delay period. The default (minimum) delay for a queue is 0 seconds. The maximum is 15 minutes. For information about configuring delay queues using the console see Configuring queue parameters using the Amazon SQS console. Best practices 85 Amazon Simple Queue Service Developer Guide Note For standard queues, the per-queue delay setting is not retroactive—changing the setting doesn't affect the delay of messages already in the queue. For FIFO queues, the per-queue delay setting is retroactive—changing the setting affects the delay of messages already in the queue. Delay queues are similar to visibility timeouts because both features make messages unavailable to consumers for a specific period of time. The difference between the two is that, for delay queues, a message is hidden when it is first added to queue, whereas for visibility timeouts a message is hidden only after it is consumed from the queue. The following diagram illustrates the relationship between delay queues and visibility timeouts. Extended scheduling options While Amazon SQS delay queues and message timers allow scheduling of message delivery up to 15 minutes in the future, you may require more flexible scheduling capabilities. In such cases, consider using EventBridge Scheduler, which enables you to schedule billions of one-time or recurring API actions without time limitations. EventBridge Scheduler is the recommended solution for advanced message scheduling use cases. To set delay seconds on individual messages, rather than on an entire queue, use message timers to allow Amazon SQS to use the message timer's DelaySeconds value instead of the delay queue's DelaySeconds value. EventBridge Scheduler also supports scheduling individual messages. Delay queues 86 Amazon Simple Queue Service Developer Guide Amazon SQS temporary queues Temporary queues help you save development time and deployment costs when using common message patterns such as request-response. You can use the Temporary Queue Client to create high-throughput, cost-effective, application-managed temporary queues. The client maps multiple temporary queues—application-managed queues created on demand for a particular process—onto a single Amazon SQS queue automatically. This allows your application to make fewer API calls and have a higher throughput when the traffic to each temporary queue is low. When a temporary queue is no longer in use, the client cleans up the temporary queue automatically, even if some processes that use the client aren't shut down cleanly. The following are the benefits of temporary queues: • They serve as lightweight communication channels for specific threads or processes. • They can be created and deleted without incurring additional cost. • They are API-compatible with static (normal) Amazon SQS queues. This means that existing code that sends and receives messages can send messages to and receive messages from virtual queues. Virtual queues Virtual queues are local data structures that the Temporary Queue Client creates. Virtual queues let you combine multiple low-traffic destinations into a single Amazon SQS queue. For best practices, see Avoid reusing the same message group ID with virtual queues. Note • Creating a virtual queue creates only temporary data structures for consumers to receive messages in. Because a virtual queue makes no API calls to Amazon SQS, virtual queues incur no cost. • TPS quotas apply to all virtual queues across a single host queue. For more information, see Amazon SQS message quotas. Temporary queues 87 Amazon Simple Queue Service Developer Guide The AmazonSQSVirtualQueuesClient wrapper class adds support for attributes related to virtual queues. To create a virtual queue, you must call the CreateQueue API action using the HostQueueURL attribute. This attribute specifies the existing queue that hosts the virtual queues. The URL of a virtual queue is in the following format. https://sqs.us-east-2.amazonaws.com/123456789012/MyQueue#MyVirtualQueueName When a producer calls the SendMessage or SendMessageBatch API action on a virtual queue URL, the Temporary Queue Client does the following: 1. Extracts the virtual queue name. 2. Attaches the virtual queue name as an additional message attribute. 3. Sends the message to the host queue. While the producer sends messages, a background thread polls the host queue and sends received messages to virtual queues according to the corresponding message attributes. While the consumer calls the ReceiveMessage API action on a virtual queue URL, the Temporary Queue Client blocks the call locally until the background thread sends a message into the virtual
|
sqs-dg-034
|
sqs-dg.pdf
| 34 |
calls the SendMessage or SendMessageBatch API action on a virtual queue URL, the Temporary Queue Client does the following: 1. Extracts the virtual queue name. 2. Attaches the virtual queue name as an additional message attribute. 3. Sends the message to the host queue. While the producer sends messages, a background thread polls the host queue and sends received messages to virtual queues according to the corresponding message attributes. While the consumer calls the ReceiveMessage API action on a virtual queue URL, the Temporary Queue Client blocks the call locally until the background thread sends a message into the virtual queue. (This process is similar to message prefetching in the Buffered Asynchronous Client: a single API action can provide messages to up to 10 virtual queues.) Deleting a virtual queue removes any client-side resources without calling Amazon SQS itself. The AmazonSQSTemporaryQueuesClient class turns all queues it creates into temporary queues automatically. It also creates host queues with the same queue attributes automatically, on demand. These queues' names share a common, configurable prefix (by default, __RequesterClientQueues__) that identifies them as temporary queues. This allows the client to act as a drop-in replacement that optimizes existing code which creates and deletes queues. The client also includes the AmazonSQSRequester and AmazonSQSResponder interfaces that allow two-way communication between queues. Request-response messaging pattern (virtual queues) The most common use case for temporary queues is the request-response messaging pattern, where a requester creates a temporary queue for receiving each response message. To avoid creating an Amazon SQS queue for each response message, the Temporary Queue Client lets you Request-response messaging pattern (virtual queues) 88 Amazon Simple Queue Service Developer Guide create and delete multiple temporary queues without making any Amazon SQS API calls. For more information, see Implementing request-response systems. The following diagram shows a common configuration using this pattern. Example scenario: Processing a login request The following example scenario shows how you can use the AmazonSQSRequester and AmazonSQSResponder interfaces to process a user's login request. On the client side public class LoginClient { // Specify the Amazon SQS queue to which to send requests. private final String requestQueueUrl; // Use the AmazonSQSRequester interface to create // a temporary queue for each response. private final AmazonSQSRequester sqsRequester = Example scenario: Processing a login request 89 Amazon Simple Queue Service Developer Guide AmazonSQSRequesterClientBuilder.defaultClient(); LoginClient(String requestQueueUrl) { this.requestQueueUrl = requestQueueUrl; } // Send a login request. public String login(String body) throws TimeoutException { SendMessageRequest request = new SendMessageRequest() .withMessageBody(body) .withQueueUrl(requestQueueUrl); // If no response is received, in 20 seconds, // trigger the TimeoutException. Message reply = sqsRequester.sendMessageAndGetResponse(request, 20, TimeUnit.SECONDS); return reply.getBody(); } } Sending a login request does the following: 1. Creates a temporary queue. 2. Attaches the temporary queue's URL to the message as an attribute. 3. Sends the message. 4. Receives a response from the temporary queue. 5. Deletes the temporary queue. 6. Returns the response. On the server side The following example assumes that, upon construction, a thread is created to poll the queue and call the handleLoginRequest() method for every message. In addition, doLogin() is an assumed method. public class LoginServer { // Specify the Amazon SQS queue to poll for login requests. private final String requestQueueUrl; Example scenario: Processing a login request 90 Amazon Simple Queue Service Developer Guide // Use the AmazonSQSResponder interface to take care // of sending responses to the correct response destination. private final AmazonSQSResponder sqsResponder = AmazonSQSResponderClientBuilder.defaultClient(); LoginServer(String requestQueueUrl) { this.requestQueueUrl = requestQueueUrl; } // Process login requests from the client. public void handleLoginRequest(Message message) { // Process the login and return a serialized result. String response = doLogin(message.getBody()); // Extract the URL of the temporary queue from the message attribute // and send the response to the temporary queue. sqsResponder.sendResponseMessage(MessageContent.fromMessage(message), new MessageContent(response)); } } Cleaning up queues To make sure that Amazon SQS reclaims any in-memory resources used by virtual queues, when your application no longer needs the Temporary Queue Client, it should call the shutdown() method. You can also use the shutdown() method of the AmazonSQSRequester interface. The Temporary Queue Client also provides a way to eliminate orphaned host queues. For each queue that receives an API call over a period of time (by default, five minutes), the client uses the TagQueue API action to tag a queue that remains in use. Note Any API action taken on a queue marks it as non-idle, including a ReceiveMessage action that returns no messages. The background thread uses the ListQueues and ListTags API actions to check all queues with the configured prefix, deleting any queues that haven't been tagged for at least five minutes. In Cleaning up queues 91 Amazon Simple Queue Service Developer Guide this way, if one client doesn't shut down cleanly, the other active clients clean up after it. In order to reduce the duplication
|
sqs-dg-035
|
sqs-dg.pdf
| 35 |
minutes), the client uses the TagQueue API action to tag a queue that remains in use. Note Any API action taken on a queue marks it as non-idle, including a ReceiveMessage action that returns no messages. The background thread uses the ListQueues and ListTags API actions to check all queues with the configured prefix, deleting any queues that haven't been tagged for at least five minutes. In Cleaning up queues 91 Amazon Simple Queue Service Developer Guide this way, if one client doesn't shut down cleanly, the other active clients clean up after it. In order to reduce the duplication of work, all clients with the same prefix communicate through a shared, internal work queue named after the prefix. Amazon SQS message timers Message timers allow you to set an initial invisibility period for a message when it's added to a queue. For example, if you send a message with a 45-second timer, it remains hidden from consumers for the first 45 seconds. The default (minimum) delay for a message is 0 seconds. The maximum is 15 minutes. For information about sending messages with timers using the console, see Sending a message using a standard queue. Note FIFO queues don't support timers on individual messages. To set a delay period on an entire queue, rather than on individual messages, use delay queues. A message timer setting for an individual message overrides any DelaySeconds value on an Amazon SQS delay queue. Extended scheduling options While Amazon SQS delay queues and message timers allow scheduling of message delivery up to 15 minutes in the future, you may require more flexible scheduling capabilities. In such cases, consider using EventBridge Scheduler, which enables you to schedule billions of one-time or recurring API actions without time limitations. EventBridge Scheduler is the recommended solution for advanced message scheduling use cases. Accessing Amazon EventBridge Pipes through the Amazon SQS console Amazon EventBridge Pipes connect sources to targets. Pipes are intended for point-to-point integrations between supported sources and targets, with support for advanced transformations and enrichment. EventBridge Pipes provide a highly scalable way to connect your Amazon SQS queue to AWS services such as Step Functions, Amazon SQS, and API Gateway, as well as third- party software as a service (SaaS) applications like Salesforce. Message timers 92 Amazon Simple Queue Service Developer Guide To set up a pipe, you choose the source, add optional filtering, define optional enrichment, and choose the target for the event data. On the details page for an Amazon SQS queue, you can view the pipes that use that queue as their source. From there, you can also: • Launch the EventBridge console to view pipe details. • Launch the EventBridge console to create a new pipe with the queue as its source. For more information on configuring an Amazon SQS queue as a pipe source, see Amazon SQS queue as a source in the Amazon EventBridge User Guide. For more information about EventBridge Pipes in general, see EventBridge Pipes. To access EventBridge pipes for a given Amazon SQS queue 1. Open the Queues page of the Amazon SQS console. 2. Select a queue. 3. On the queue detail page, choose the EventBridge Pipes tab. The EventBridge Pipes tab includes a list of any pipes currently configured to use the selected queue as a source, including: • pipe name • current status • pipe target • when the pipe was last modified 4. View more pipe details or create a new pipe, if desired: • To access more details about a pipe: Choose the pipe name. This launches the Pipe details page of the EventBridge console. • To create a new pipe: Choose Connect Amazon SQS queue to pipe. Accessing EventBridge pipes 93 Amazon Simple Queue Service Developer Guide This launches the Create pipe page of the EventBridge console, with the Amazon SQS queue specified as the pipe source. For more information, see Creating an EventBridge pipe in the Amazon EventBridge User Guide. Important A message on an Amazon SQS queue is read by a single pipe and then deleted from the queue after being processed, whether or not the message matches the filter you can configured for that pipe. Proceed with caution when configuring multiple pipes to use the same queue as their source. Managing large Amazon SQS messages with Extended Client Library and Amazon Simple Storage Service Use the Amazon SQS Extended Client Library for Java and Amazon SQS Extended Client Library for Python to send large messages, especially for payloads between 256 KB and 2 GB. These libraries store the message payload in an Amazon S3 bucket and send a reference to the stored object in the Amazon SQS queue. Note The Amazon SQS Extended Client Libraries are compatible with both standard and FIFO queues. Managing large Amazon SQS messages using
|
sqs-dg-036
|
sqs-dg.pdf
| 36 |
configuring multiple pipes to use the same queue as their source. Managing large Amazon SQS messages with Extended Client Library and Amazon Simple Storage Service Use the Amazon SQS Extended Client Library for Java and Amazon SQS Extended Client Library for Python to send large messages, especially for payloads between 256 KB and 2 GB. These libraries store the message payload in an Amazon S3 bucket and send a reference to the stored object in the Amazon SQS queue. Note The Amazon SQS Extended Client Libraries are compatible with both standard and FIFO queues. Managing large Amazon SQS messages using Java and Amazon S3 Use the Amazon SQS Extended Client Library for Java with Amazon S3 to manage large Amazon SQS messages, particularly for payloads ranging from 256 KB to 2 GB. The library stores the message payload in an Amazon S3 bucket and sends a message containing a reference to the stored object in the Amazon SQS queue. With the Amazon SQS Extended Client Library for Java, you can: • Specify whether messages are always stored in Amazon S3 or only when the size of a message exceeds 256 KB Managing large messages 94 Amazon Simple Queue Service Developer Guide • Send a message that references a single message object stored in an S3 bucket • Retrieve the message object from an Amazon S3 bucket • Delete the message object from an Amazon S3 bucket Prerequisites The following example uses the AWS Java SDK. To install and set up the SDK, see Set up the AWS SDK for Java in the AWS SDK for Java Developer Guide. Before you run the example code, configure your AWS credentials. For more information, see Set up AWS Credentials and Region for Development in the AWS SDK for Java Developer Guide. The SDK for Java and Amazon SQS Extended Client Library for Java require the J2SE Development Kit 8.0 or later. Note You can use the Amazon SQS Extended Client Library for Java to manage Amazon SQS messages using Amazon S3 only with the AWS SDK for Java. You can't do this with the AWS CLI, the Amazon SQS console, the Amazon SQS HTTP API, or any of the other AWS SDKs. AWS SDK for Java 2.x Example: Using Amazon S3 to manage large Amazon SQS messages The following SDK for Java 2.x example creates an Amazon S3 bucket with a random name and adds a lifecycle rule to permanently delete objects after 14 days. It also creates a queue named MyQueue and sends a random message that is stored in an Amazon S3 bucket and is more than 256 KB to the queue. Finally, the code retrieves the message, returns information about it, and then deletes the message, the queue, and the bucket. /* * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://aws.amazon.com/apache2.0 Using the Extended Client Library for Java 95 Amazon Simple Queue Service * Developer Guide * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ import com.amazon.sqs.javamessaging.AmazonSQSExtendedClient; import com.amazon.sqs.javamessaging.ExtendedClientConfiguration; import org.joda.time.DateTime; import org.joda.time.format.DateTimeFormat; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.BucketLifecycleConfiguration; import software.amazon.awssdk.services.s3.model.CreateBucketRequest; import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; import software.amazon.awssdk.services.s3.model.ExpirationStatus; import software.amazon.awssdk.services.s3.model.LifecycleExpiration; import software.amazon.awssdk.services.s3.model.LifecycleRule; import software.amazon.awssdk.services.s3.model.LifecycleRuleFilter; import software.amazon.awssdk.services.s3.model.ListObjectVersionsRequest; import software.amazon.awssdk.services.s3.model.ListObjectVersionsResponse; import software.amazon.awssdk.services.s3.model.ListObjectsV2Request; import software.amazon.awssdk.services.s3.model.ListObjectsV2Response; import software.amazon.awssdk.services.s3.model.PutBucketLifecycleConfigurationRequest; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.CreateQueueResponse; import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest; import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest; import software.amazon.awssdk.services.sqs.model.Message; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; import software.amazon.awssdk.services.sqs.model.ReceiveMessageResponse; import software.amazon.awssdk.services.sqs.model.SendMessageRequest; import java.util.Arrays; import java.util.List; import java.util.UUID; /** * Examples of using Amazon SQS Extended Client Library for Java 2.x * Using the Extended Client Library for Java 96 Amazon Simple Queue Service */ Developer Guide public class SqsExtendedClientExamples { // Create an Amazon S3 bucket with a random name. private final static String amzn-s3-demo-bucket = UUID.randomUUID() + "-" + DateTimeFormat.forPattern("yyMMdd-hhmmss").print(new DateTime()); public static void main(String[] args) { /* * Create a new instance of the builder with all defaults (credentials * and region) set automatically. For more information, see * Creating Service Clients in the AWS SDK for Java Developer Guide. */ final S3Client s3 = S3Client.create(); /* * Set the Amazon S3 bucket name, and then set a lifecycle rule on the * bucket to permanently delete objects 14 days after each object's * creation date. */ final LifecycleRule lifeCycleRule = LifecycleRule.builder() .expiration(LifecycleExpiration.builder().days(14).build()) .filter(LifecycleRuleFilter.builder().prefix("").build()) .status(ExpirationStatus.ENABLED) .build(); final BucketLifecycleConfiguration lifecycleConfig = BucketLifecycleConfiguration.builder() .rules(lifeCycleRule) .build(); // Create the bucket and configure it s3.createBucket(CreateBucketRequest.builder().bucket(amzn-s3-demo- bucket).build()); s3.putBucketLifecycleConfiguration(PutBucketLifecycleConfigurationRequest.builder() .bucket(amzn-s3-demo-bucket) .lifecycleConfiguration(lifecycleConfig) .build()); System.out.println("Bucket created and configured."); // Set the
|
sqs-dg-037
|
sqs-dg.pdf
| 37 |
the builder with all defaults (credentials * and region) set automatically. For more information, see * Creating Service Clients in the AWS SDK for Java Developer Guide. */ final S3Client s3 = S3Client.create(); /* * Set the Amazon S3 bucket name, and then set a lifecycle rule on the * bucket to permanently delete objects 14 days after each object's * creation date. */ final LifecycleRule lifeCycleRule = LifecycleRule.builder() .expiration(LifecycleExpiration.builder().days(14).build()) .filter(LifecycleRuleFilter.builder().prefix("").build()) .status(ExpirationStatus.ENABLED) .build(); final BucketLifecycleConfiguration lifecycleConfig = BucketLifecycleConfiguration.builder() .rules(lifeCycleRule) .build(); // Create the bucket and configure it s3.createBucket(CreateBucketRequest.builder().bucket(amzn-s3-demo- bucket).build()); s3.putBucketLifecycleConfiguration(PutBucketLifecycleConfigurationRequest.builder() .bucket(amzn-s3-demo-bucket) .lifecycleConfiguration(lifecycleConfig) .build()); System.out.println("Bucket created and configured."); // Set the Amazon SQS extended client configuration with large payload support enabled final ExtendedClientConfiguration extendedClientConfig = new ExtendedClientConfiguration().withPayloadSupportEnabled(s3, amzn-s3-demo-bucket); Using the Extended Client Library for Java 97 Amazon Simple Queue Service Developer Guide final SqsClient sqsExtended = new AmazonSQSExtendedClient(SqsClient.builder().build(), extendedClientConfig); // Create a long string of characters for the message object int stringLength = 300000; char[] chars = new char[stringLength]; Arrays.fill(chars, 'x'); final String myLongString = new String(chars); // Create a message queue for this example final String queueName = "MyQueue-" + UUID.randomUUID(); final CreateQueueResponse createQueueResponse = sqsExtended.createQueue(CreateQueueRequest.builder().queueName(queueName).build()); final String myQueueUrl = createQueueResponse.queueUrl(); System.out.println("Queue created."); // Send the message final SendMessageRequest sendMessageRequest = SendMessageRequest.builder() .queueUrl(myQueueUrl) .messageBody(myLongString) .build(); sqsExtended.sendMessage(sendMessageRequest); System.out.println("Sent the message."); // Receive the message final ReceiveMessageResponse receiveMessageResponse = sqsExtended.receiveMessage(ReceiveMessageRequest.builder().queueUrl(myQueueUrl).build()); List<Message> messages = receiveMessageResponse.messages(); // Print information about the message for (Message message : messages) { System.out.println("\nMessage received."); System.out.println(" ID: " + message.messageId()); System.out.println(" Receipt handle: " + message.receiptHandle()); System.out.println(" Message body (first 5 characters): " + message.body().substring(0, 5)); } // Delete the message, the queue, and the bucket final String messageReceiptHandle = messages.get(0).receiptHandle(); sqsExtended.deleteMessage(DeleteMessageRequest.builder().queueUrl(myQueueUrl).receiptHandle(messageReceiptHandle).build()); System.out.println("Deleted the message."); Using the Extended Client Library for Java 98 Amazon Simple Queue Service Developer Guide sqsExtended.deleteQueue(DeleteQueueRequest.builder().queueUrl(myQueueUrl).build()); System.out.println("Deleted the queue."); deleteBucketAndAllContents(s3); System.out.println("Deleted the bucket."); } private static void deleteBucketAndAllContents(S3Client client) { ListObjectsV2Response listObjectsResponse = client.listObjectsV2(ListObjectsV2Request.builder().bucket(amzn-s3-demo- bucket).build()); listObjectsResponse.contents().forEach(object -> { client.deleteObject(DeleteObjectRequest.builder().bucket(amzn-s3-demo- bucket).key(object.key()).build()); }); ListObjectVersionsResponse listVersionsResponse = client.listObjectVersions(ListObjectVersionsRequest.builder().bucket(amzn-s3-demo- bucket).build()); listVersionsResponse.versions().forEach(version -> { client.deleteObject(DeleteObjectRequest.builder().bucket(amzn-s3-demo- bucket).key(version.key()).versionId(version.versionId()).build()); }); client.deleteBucket(DeleteBucketRequest.builder().bucket(amzn-s3-demo- bucket).build()); } } You can use Apache Maven to configure and build Amazon SQS Extended Client for your Java project, or to build the SDK itself. Specify individual modules from the SDK that you use in your application. <properties> <aws-java-sdk.version>2.20.153</aws-java-sdk.version> </properties> Using the Extended Client Library for Java 99 Amazon Simple Queue Service Developer Guide <dependencies> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>sqs</artifactId> <version>${aws-java-sdk.version}</version> </dependency> <dependency> <groupId>software.amazon.awssdk</groupId> <artifactId>s3</artifactId> <version>${aws-java-sdk.version}</version> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>amazon-sqs-java-extended-client-lib</artifactId> <version>2.0.4</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.12.6</version> </dependency> </dependencies> Managing large Amazon SQS messages using Python and Amazon S3 Use the Amazon SQS Amazon SQS Extended Client Library for Python with Amazon S3 to manage large Amazon SQS messages, especially for payloads between 256 KB and 2 GB. The library stores the message payload in an Amazon S3 bucket and sends a message containing a reference to the stored object in the Amazon SQS queue. With the Amazon SQS Extended Client Library for Python, you can: • Specify whether payloads are always stored in Amazon S3, or only stored in Amazon S3 when a payload size exceeds 256 KB • Send a message that references a single message object stored in an Amazon S3 bucket • Retrieve the corresponding payload object from an Amazon S3 bucket • Delete the corresponding payload object from an Amazon S3 bucket Using the Extended Client Library for Python 100 Amazon Simple Queue Service Prerequisites Developer Guide The following are the prerequisites for using the Amazon SQS Extended Client Library for Python: • An AWS account with the necessary credentials. To create an AWS account, navigate to the AWS home page , and then choose Create an AWS Account . Follow the instructions. For information about credentials, see Credentials. • An AWS SDK: The example on this page uses AWS Python SDK Boto3. To install and set up the SDK, see the AWS SDK for Python documentation in the AWS SDK for Python Developer Guide • Python 3.x (or later) and pip. • The Amazon SQS Extended Client Library for Python, available from PyPI Note You can use the Amazon SQS Extended Client Library for Python to manage Amazon SQS messages using Amazon S3 only with the AWS SDK for Python. You can't do this with the AWS CLI, the Amazon SQS console, the Amazon SQS HTTP API, or any of the other AWS SDKs. Configuring message storage The Amazon SQS Extended Client makes uses the following message attributes to configure the Amazon S3 message storage options: • large_payload_support: The Amazon S3 bucket name to store large messages. • always_through_s3: If True, then all messages are stored in Amazon S3. If False, messages smaller than 256 KB will not be serialized to the s3 bucket. The default is False. • use_legacy_attribute: If True, all published messages use the Legacy reserved message attribute (SQSLargePayloadSize) instead of the current reserved message
|
sqs-dg-038
|
sqs-dg.pdf
| 38 |
the Amazon SQS console, the Amazon SQS HTTP API, or any of the other AWS SDKs. Configuring message storage The Amazon SQS Extended Client makes uses the following message attributes to configure the Amazon S3 message storage options: • large_payload_support: The Amazon S3 bucket name to store large messages. • always_through_s3: If True, then all messages are stored in Amazon S3. If False, messages smaller than 256 KB will not be serialized to the s3 bucket. The default is False. • use_legacy_attribute: If True, all published messages use the Legacy reserved message attribute (SQSLargePayloadSize) instead of the current reserved message attribute (ExtendedPayloadSize). Managing large Amazon SQS messages with Extended Client Library for Python The following example creates an Amazon S3 bucket with a random name. It then creates an Amazon SQS queue named MyQueue and sends a message that is stored in an S3 bucket and is Using the Extended Client Library for Python 101 Amazon Simple Queue Service Developer Guide more than 256 KB to the queue. Finally, the code retrieves the message, returns information about it, and then deletes the message, the queue, and the bucket. import boto3 import sqs_extended_client #Set the Amazon SQS extended client configuration with large payload. sqs_extended_client = boto3.client("sqs", region_name="us-east-1") sqs_extended_client.large_payload_support = "amzn-s3-demo-bucket" sqs_extended_client.use_legacy_attribute = False # Create an SQS message queue for this example. Then, extract the queue URL. queue = sqs_extended_client.create_queue( QueueName = "MyQueue" ) queue_url = sqs_extended_client.get_queue_url( QueueName = "MyQueue" )['QueueUrl'] # Create the S3 bucket and allow message objects to be stored in the bucket. sqs_extended_client.s3_client.create_bucket(Bucket=sqs_extended_client.large_payload_support) # Sending a large message small_message = "s" large_message = small_message * 300000 # Shall cross the limit of 256 KB send_message_response = sqs_extended_client.send_message( QueueUrl=queue_url, MessageBody=large_message ) assert send_message_response['ResponseMetadata']['HTTPStatusCode'] == 200 # Receiving the large message receive_message_response = sqs_extended_client.receive_message( QueueUrl=queue_url, MessageAttributeNames=['All'] ) assert receive_message_response['Messages'][0]['Body'] == large_message receipt_handle = receive_message_response['Messages'][0]['ReceiptHandle'] Using the Extended Client Library for Python 102 Amazon Simple Queue Service # Deleting the large message # Set to True for deleting the payload from S3 sqs_extended_client.delete_payload_from_s3 = True delete_message_response = sqs_extended_client.delete_message( QueueUrl=queue_url, ReceiptHandle=receipt_handle ) Developer Guide assert delete_message_response['ResponseMetadata']['HTTPStatusCode'] == 200 # Deleting the queue delete_queue_response = sqs_extended_client.delete_queue( QueueUrl=queue_url ) assert delete_queue_response['ResponseMetadata']['HTTPStatusCode'] == 200 Using the Extended Client Library for Python 103 Amazon Simple Queue Service Developer Guide Configuring Amazon SQS queues using the Amazon SQS console Use the Amazon SQS console to configure and manage Amazon SQS queues and features. You can also: • Enable server-side encryption for enhanced security. • Associate a dead-letter queue to handle unprocessed messages. • Set up a trigger to invoke an Lambda function for event-driven processing. Attribute-based access control for Amazon SQS What is ABAC? Attribute-based access control (ABAC) is an authorization process that defines permissions based on tags that are attached to users and AWS resources. ABAC provides granular and flexible access control based on attributes and values, reduces security risk related to reconfigured role-based policies, and centralizes auditing and access policy management. For more details about ABAC, see What is ABAC for AWS in the IAM User Guide. Amazon SQS supports ABAC by allowing you to control access to your Amazon SQS queues based on the tags and aliases that are associated with an Amazon SQS queue. The tag and alias condition keys that enable ABAC in Amazon SQS authorize IAM principals to use Amazon SQS queues without editing policies or managing grants. To learn more about ABAC condition keys, see Condition keys for Amazon SQS in the Service Authorization Reference. With ABAC, you can use tags to configure IAM access permissions and policies for your Amazon SQS queues, which helps you to scale your permissions management. You can create a single permissions policy in IAM using tags that you add to each business role—without having to update the policy each time you add a new resource. You can also attach tags to IAM principals to create an ABAC policy. You can design ABAC policies to allow Amazon SQS operations when the tag on the IAM user role that's making the call matches the Amazon SQS queue tag. To learn more about tagging in AWS, see AWS Tagging Strategies and Amazon SQS cost allocation tags. ABAC for Amazon SQS 104 Amazon Simple Queue Service Developer Guide Note ABAC for Amazon SQS is currently available in all AWS Commercial Regions where Amazon SQS is available, with the following exceptions: • Asia Pacific (Hyderabad) • Asia Pacific (Melbourne) • Europe (Spain) • Europe (Zurich) Why should I use ABAC in Amazon SQS? Here are some benefits of using ABAC in Amazon SQS: • ABAC for Amazon SQS requires fewer permissions policies. You don't have to create different policies for different job functions. You can use resource and request tags that apply to more than one queue, which reduces operational overhead. • Use ABAC to scale teams quickly.
|
sqs-dg-039
|
sqs-dg.pdf
| 39 |
Guide Note ABAC for Amazon SQS is currently available in all AWS Commercial Regions where Amazon SQS is available, with the following exceptions: • Asia Pacific (Hyderabad) • Asia Pacific (Melbourne) • Europe (Spain) • Europe (Zurich) Why should I use ABAC in Amazon SQS? Here are some benefits of using ABAC in Amazon SQS: • ABAC for Amazon SQS requires fewer permissions policies. You don't have to create different policies for different job functions. You can use resource and request tags that apply to more than one queue, which reduces operational overhead. • Use ABAC to scale teams quickly. Permissions for new resources are automatically granted based on tags when resources are appropriately tagged during their creation. • Use permissions on the IAM principal to restrict resource access. You can create tags for the IAM principal and use them to restrict access to specific actions that match the tags on the IAM principal. This helps you to automate the process of granting request permissions. • Track who's accessing your resources. You can determine the identity of a session by looking at user attributes in AWS CloudTrail. Topics • Tagging for access control in Amazon SQS • Creating IAM users and Amazon SQS queues • Testing attribute-based access control in Amazon SQS Tagging for access control in Amazon SQS The following is an example of using tags for access control in Amazon SQS. The IAM policy restricts an IAM user to all Amazon SQS actions for all queues that include a resource tag with Why should I use ABAC in Amazon SQS? 105 Amazon Simple Queue Service Developer Guide the key environment and the value production. For more information, see Attribute-based access control with tags and AWS Organizations. { "Version": "2012-10-17", "Statement": [ { "Sid": "DenyAccessForProd", "Effect": "Deny", "Action": "sqs:*", "Resource": "*", "Condition": { "StringEquals": { "aws:ResourceTag/environment": "prod" } } } ] } Creating IAM users and Amazon SQS queues The following examples explain how to create an ABAC policy to control access to Amazon SQS using the AWS Management Console and AWS CloudFormation. Using the AWS Management Console Create an IAM user 1. Sign in to the AWS Management Console and open the IAM console at https:// console.aws.amazon.com/iam/. 2. Choose User from the left navigation pane. 3. Choose Add Users and enter a name in the User name text box. 4. Select the Access key - Programmatic access box and choose Next:Permissions. 5. Choose Next:Tags. 6. Add the tag key as environment and the tag value as beta. 7. Choose Next:Review and then choose Create user. 8. Copy and store the access key ID and secret access key in a secure location. Creating IAM users and Amazon SQS queues 106 Developer Guide Amazon Simple Queue Service Add IAM user permissions 1. Select the IAM user that you created. 2. Choose Add inline policy. 3. On the JSON tab, paste the following policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowAccessForSameResTag", "Effect": "Allow", "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage", "sqs:DeleteMessage" ], "Resource": "*", "Condition": { "StringEquals": { "aws:ResourceTag/environment": "${aws:PrincipalTag/environment}" } } }, { "Sid": "AllowAccessForSameReqTag", "Effect": "Allow", "Action": [ "sqs:CreateQueue", "sqs:DeleteQueue", "sqs:SetQueueAttributes", "sqs:tagqueue" ], "Resource": "*", "Condition": { "StringEquals": { "aws:RequestTag/environment": "${aws:PrincipalTag/environment}" } } }, { "Sid": "DenyAccessForProd", "Effect": "Deny", Creating IAM users and Amazon SQS queues 107 Amazon Simple Queue Service Developer Guide "Action": "sqs:*", "Resource": "*", "Condition": { "StringEquals": { "aws:ResourceTag/stage": "prod" } } } ] } 4. Choose Review policy. 5. Choose Create policy. Using AWS CloudFormation Use the following sample AWS CloudFormation template to create an IAM user with an inline policy attached and an Amazon SQS queue: AWSTemplateFormatVersion: "2010-09-09" Description: "CloudFormation template to create IAM user with custom inline policy" Resources: IAMPolicy: Type: "AWS::IAM::Policy" Properties: PolicyDocument: | { "Version": "2012-10-17", "Statement": [ { "Sid": "AllowAccessForSameResTag", "Effect": "Allow", "Action": [ "sqs:SendMessage", "sqs:ReceiveMessage", "sqs:DeleteMessage" ], "Resource": "*", "Condition": { "StringEquals": { "aws:ResourceTag/environment": "${aws:PrincipalTag/ environment}" Creating IAM users and Amazon SQS queues 108 Amazon Simple Queue Service Developer Guide } } }, { "Sid": "AllowAccessForSameReqTag", "Effect": "Allow", "Action": [ "sqs:CreateQueue", "sqs:DeleteQueue", "sqs:SetQueueAttributes", "sqs:tagqueue" ], "Resource": "*", "Condition": { "StringEquals": { "aws:RequestTag/environment": "${aws:PrincipalTag/ environment}" } } }, { "Sid": "DenyAccessForProd", "Effect": "Deny", "Action": "sqs:*", "Resource": "*", "Condition": { "StringEquals": { "aws:ResourceTag/stage": "prod" } } } ] } Users: - "testUser" PolicyName: tagQueuePolicy IAMUser: Type: "AWS::IAM::User" Properties: Path: "/" UserName: "testUser" Tags: Creating IAM users and Amazon SQS queues 109 Amazon Simple Queue Service - Key: "environment" Value: "beta" Developer Guide Testing attribute-based access control in Amazon SQS The following examples show you how to test attribute-based access control in Amazon SQS. Create a queue with the tag key set to environment and the tag value set to prod Run this AWS CLI command to test creating the queue with the tag key set to environment and the tag value set to
|
sqs-dg-040
|
sqs-dg.pdf
| 40 |
"prod" } } } ] } Users: - "testUser" PolicyName: tagQueuePolicy IAMUser: Type: "AWS::IAM::User" Properties: Path: "/" UserName: "testUser" Tags: Creating IAM users and Amazon SQS queues 109 Amazon Simple Queue Service - Key: "environment" Value: "beta" Developer Guide Testing attribute-based access control in Amazon SQS The following examples show you how to test attribute-based access control in Amazon SQS. Create a queue with the tag key set to environment and the tag value set to prod Run this AWS CLI command to test creating the queue with the tag key set to environment and the tag value set to prod. If you don't have AWS CLI, you can download and configure it for your machine. aws sqs create-queue --queue-name prodQueue —region us-east-1 —tags "environment=prod" You receive an AccessDenied error from the Amazon SQS endpoint: An error occurred (AccessDenied) when calling the CreateQueue operation: Access to the resource <queueUrl> is denied. This is because the tag value on the IAM user does not match the tag passed in the CreateQueue API call. Remember that we applied a tag to the IAM user with the key set to environment and the value set to beta. Create a queue with the tag key set to environment and the tag value set to beta Run the this CLI command to test creating a queue with the tag key set to environment and the tag value set to beta. aws sqs create-queue --queue-name betaQueue —region us-east-1 —tags "environment=beta" You receive a message confirming the successful creation of the queue, similar to the one below. { "QueueUrl": "<queueUrl>“ } Testing attribute-based access control 110 Amazon Simple Queue Service Developer Guide Sending a message to a queue Run this CLI command to test sending a message to a queue. aws sqs send-message --queue-url <queueUrl> --message-body testMessage The response shows a successful message delivery to the Amazon SQS queue. The IAM user permission allows you to send a message to a queue that has a beta tag. The response includes MD5OfMessageBody and MessageId containing the message. { "MD5OfMessageBody": "<MD5OfMessageBody>", "MessageId": "<MessageId>" } Configuring queue parameters using the Amazon SQS console When creating or editing a queue, you can configure the following parameters: • Visibility timeout – The length of time that a message received from a queue (by one consumer) won't be visible to the other message consumers. For more information, see Visibility timeout. Note Using the console to configure the visibility timeout configures the timeout value for all of the messages in the queue. To configure the timeout for single or multiple messages, you must use one of the AWS SDKs. • Message retention period – The amount of time that Amazon SQS retains messages that remain in the queue. By default, the queue retains messages for four days. You can configure a queue to retain messages for up to 14 days. For more information, see Message retention period. • Delivery delay – The amount of time that Amazon SQS will delay before delivering a message that is added to the queue. For more information, see Delivery delay. • Maximum message size – The maximum message size for this queue. For more information, see Maximum message size. • Receive message wait time – The maximum amount of time that Amazon SQS waits for messages to become available after the queue gets a receive request. For more information, see Amazon SQS short and long polling. Configuring queue parameters 111 Amazon Simple Queue Service Developer Guide • Enable content-based deduplication – Amazon SQS can automatically create deduplication IDs based on the body of the message. For more information, see Amazon SQS FIFO queues. • Enable high throughput FIFO – Use to enable high throughput for messages in the queue. Choosing this option changes the related options (Deduplication scope and FIFO throughput limit) to the required settings for enabling high throughput for FIFO queues. For more information, see High throughput for FIFO queues in Amazon SQS and Amazon SQS message quotas. • Redrive allow policy: defines which source queues can use this queue as the dead-letter queue. For more information, see Using dead-letter queues in Amazon SQS . To configure queue parameters for an existing queue (console) 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. 3. 4. 5. 6. 7. 8. 9. In the navigation pane, choose Queues. Choose a queue and choose Edit. Scroll to the Configuration section. For Visibility timeout , enter the duration and units. The range is 0 seconds to 12 hours. The default value is 30 seconds. For Message retention period, enter the duration and units. The range is 1 minute to 14 days. The default value is 4 days. For a standard queue, enter a value for Receive message wait time. The range is 0 to 20 seconds. The default value is
|
sqs-dg-041
|
sqs-dg.pdf
| 41 |
the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. 3. 4. 5. 6. 7. 8. 9. In the navigation pane, choose Queues. Choose a queue and choose Edit. Scroll to the Configuration section. For Visibility timeout , enter the duration and units. The range is 0 seconds to 12 hours. The default value is 30 seconds. For Message retention period, enter the duration and units. The range is 1 minute to 14 days. The default value is 4 days. For a standard queue, enter a value for Receive message wait time. The range is 0 to 20 seconds. The default value is 0 seconds, which sets short polling. Any non-zero value sets long polling. For Delivery delay, enter the duration and units. The range is 0 seconds to 15 minutes. The default value is 0 seconds. For Maximum message size, enter a value. The range is 1 KB to 256 KB. The default value is 256 KB. For a FIFO queue, choose Enable content-based deduplication to enable content-based deduplication. The default setting is disabled. 10. (Optional) For a FIFO queue to enable higher throughput for sending and receiving messages in the queue, choose Enable high throughput FIFO. Choosing this option changes the related options (Deduplication scope and FIFO throughput limit) to the required settings for enabling high throughput for FIFO queues. If you change any of the settings required for using high throughput FIFO, normal throughput is in effect for the Configuring queue parameters 112 Amazon Simple Queue Service Developer Guide queue, and deduplication occurs as specified. For more information, see High throughput for FIFO queues in Amazon SQS and Amazon SQS message quotas. 11. For Redrive allow policy, choose Enabled. Select from the following: Allow all (default), By queue or Deny all. When choosing By queue, specify a list of up to 10 source queues by the Amazon Resource Name (ARN). 12. When you finish configuring the queue parameters, choose Save. Configuring an access policy in Amazon SQS When you edit a queue, you can configure its access policy to control who can interact with it. • The access policy defines which accounts, users, and roles have permissions to access the queue. • It specifies the allowed actions, such as SendMessage, ReceiveMessage, or DeleteMessage. • By default, only the queue owner has permission to send and receive messages. To configure the access policy for an existing queue (console) 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. Choose a queue and choose Edit. 4. 5. Scroll to the Access policy section. Edit the access policy statements in the input box. For more on access policy statements, see Identity and access management in Amazon SQS. 6. When you finish configuring the access policy, choose Save. Configuring server-side encryption for a queue using SQS- managed encryption keys In addition to the default Amazon SQS managed server-side encryption (SSE) option, Amazon SQS managed SSE (SSE-SQS) lets you create custom managed server-side encryption that uses SQS-managed encryption keys to protect sensitive data sent over message queues. With SSE-SQS, you don't need to create and manage encryption keys, or modify your code to encrypt your data. SSE-SQS lets you transmit data securely and helps you meet strict encryption compliance and regulatory requirements at no additional cost. Configuring an access policy 113 Amazon Simple Queue Service Developer Guide SSE-SQS protects data at rest using 256-bit Advanced Encryption Standard (AES-256) encryption. SSE encrypts messages as soon as Amazon SQS receives them. Amazon SQS stores messages in encrypted form and decrypts them only when sending them to an authorized consumer. Note • The default SSE option is only effective when you create a queue without specifying encryption attributes. • Amazon SQS allows you to turn off all queue encryption. Therefore, turning off KMS-SSE, will not automatically enable SQS-SSE. If you wish to enable SQS-SSE after turning off KMS-SSE, you must add an attribute change in the request. To configure SSE-SQS encryption for a queue (console) Note Any new queue created using the HTTP (non-TLS) endpoint will not enable SSE-SQS encryption by default. It is a security best practice to create Amazon SQS queues using HTTPS or Signature Version 4 endpoints. 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. Choose a queue, and then choose Edit. 4. 5. Expand Encryption. For Server-side encryption, choose Enabled (default). Note With SSE enabled, anonymous SendMessage and ReceiveMessage requests to the encrypted queue will be rejected. Amazon SQS security best practises recommend against using anonymous requests. If you wish to send anonymous requests to an Amazon SQS queue, make sure to disable SSE. 6. Select Amazon SQS key (SSE-SQS). There is no additional fee for using this option. Configuring SSE-SQS for a queue 114 Amazon Simple Queue Service 7.
|
sqs-dg-042
|
sqs-dg.pdf
| 42 |
the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. Choose a queue, and then choose Edit. 4. 5. Expand Encryption. For Server-side encryption, choose Enabled (default). Note With SSE enabled, anonymous SendMessage and ReceiveMessage requests to the encrypted queue will be rejected. Amazon SQS security best practises recommend against using anonymous requests. If you wish to send anonymous requests to an Amazon SQS queue, make sure to disable SSE. 6. Select Amazon SQS key (SSE-SQS). There is no additional fee for using this option. Configuring SSE-SQS for a queue 114 Amazon Simple Queue Service 7. Choose Save. Developer Guide Configuring server-side encryption for a queue using the Amazon SQS console To protect the data in a queue’s messages, Amazon SQS has server-side encryption (SSE) enabled by default for all newly created queues. Amazon SQS integrates with the Amazon Web Services Key Management Service (Amazon Web Services KMS) to manage KMS keys for server-side encryption (SSE). For information about using SSE, see Encryption at rest in Amazon SQS. The KMS key that you assign to your queue must have a key policy that includes permissions for all principals that are authorized to use the queue. For information, see Key Management. If you aren't the owner of the KMS key, or if you log in with an account that doesn't have kms:ListAliases and kms:DescribeKey permissions, you won't be able to view information about the KMS key on the Amazon SQS console. Ask the owner of the KMS key to grant you these permissions. For more information, see Key Management. When you create or edit a queue, you can configure SSE-KMS. To configure SSE-KMS for an existing queue (console) 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. Choose a queue, and then choose Edit. 4. 5. Expand Encryption. For Server-side encryption, choose Enabled (default). Note With SSE enabled, anonymous SendMessage and ReceiveMessage requests to the encrypted queue will be rejected. Amazon SQS security best practises recommend against using anonymous requests. If you wish to send anonymous requests to an Amazon SQS queue, make sure to disable SSE. 6. Select AWS Key Management Service key (SSE-KMS). Configuring SSE-KMS for a queue 115 Amazon Simple Queue Service Developer Guide The console displays the Description, the Account, and the KMS key ARN of the KMS key. 7. Specify the KMS key ID for the queue. For more information, see Key terms. a. b. c. d. Choose the Choose a KMS key alias option. The default key is the Amazon Web Services managed KMS key for Amazon SQS. To use this key, choose it from the KMS key list. To use a custom KMS key from your Amazon Web Services account, choose it from the KMS key list. For instructions on creating custom KMS keys, see Creating Keys in the Amazon Web Services Key Management Service Developer Guide. To use a custom KMS key that is not in the list, or a custom KMS key from another Amazon Web Services account, choose Enter the KMS key alias and enter the KMS key Amazon Resource Name (ARN). 8. (Optional) For Data key reuse period, specify a value between 1 minute and 24 hours. The default is 5 minutes. For more information, see Understanding the data key reuse period. 9. When you finish configuring SSE-KMS, choose Save. Configuring cost allocation tags for a queue using the Amazon SQS console To organize and identify your Amazon SQS queues, you can add cost allocation tags. For more information, see Amazon SQS cost allocation tags. • The Tagging tab on the Details page displays the queue's tags. • You can add or modify tags when creating or editing a queue. To configure tags for an existing queue (console) 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. Choose a queue and choose Edit. 4. Scroll to the Tags section. 5. Add, modify, or remove the queue tags: a. To add a tag, choose Add new tag, enter a Key and Value, and then choose Add new tag. Configuring tags for a queue 116 Amazon Simple Queue Service Developer Guide b. c. To update a tag, change its Key and Value. To remove a tag, choose Remove next to its key-value pair. 6. When you finish configuring the tags, choose Save. Subscribing a queue to an Amazon SNS topic using the Amazon SQS console You can subscribe one or more Amazon SQS queues to an Amazon SNS topic. When you publish a message to a topic, Amazon SNS sends the message to each subscribed queue. Amazon SQS manages the subscription and handles the required permissions. For more information about Amazon SNS, see What is Amazon SNS? in the Amazon Simple Notification Service Developer
|
sqs-dg-043
|
sqs-dg.pdf
| 43 |
update a tag, change its Key and Value. To remove a tag, choose Remove next to its key-value pair. 6. When you finish configuring the tags, choose Save. Subscribing a queue to an Amazon SNS topic using the Amazon SQS console You can subscribe one or more Amazon SQS queues to an Amazon SNS topic. When you publish a message to a topic, Amazon SNS sends the message to each subscribed queue. Amazon SQS manages the subscription and handles the required permissions. For more information about Amazon SNS, see What is Amazon SNS? in the Amazon Simple Notification Service Developer Guide. When you subscribe an Amazon SQS queue to an Amazon SNS topic, Amazon SNS uses HTTPS to forward messages to Amazon SQS. For information about using Amazon SNS with encrypted Amazon SQS queues, see Configure KMS permissions for AWS services. Important Amazon SQS supports a maximum of 20 statements for each access policy. Subscribing to an Amazon SNS topic adds one such statement. Exceeding this amount will result in a failed topic subscription delivery. To subscribe a queue to an Amazon SNS topic (console) 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. 3. 4. 5. In the navigation pane, choose Queues. From the list of queues, choose the queue to subscribe to the Amazon SNS topic. From Actions, choose Subscribe to Amazon SNS topic. From the Specify an Amazon SNS topic available for this queue menu, choose the Amazon SNS topic for your queue. If the SNS topic isn't listed, choose Enter Amazon SNS topic ARN and then enter the topic's Amazon Resource Name (ARN). 6. Choose Save. Subscribing a queue to a topic 117 Amazon Simple Queue Service Developer Guide 7. To verify the subscription, publish a message to the topic and view the message in the queue. For more information, see Amazon SNS message publishing in the Amazon Simple Notification Service Developer Guide. Cross-account subscriptions If your Amazon SQS queue and Amazon SNS topic are in different AWS accounts, additional permissions are required. Topic owner (Account A) Modify the Amazon SNS topic's access policy to allow the Amazon SQS queue's AWS account to subscribe. Example policy statement: { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::111122223333:root" }, "Action": "sns:Subscribe", "Resource": "arn:aws:sns:us-east-1:123456789012:MyTopic" } This policy allows account 111122223333 to subscribe to MyTopic. Queue owner (Account B) Modify the Amazon SQS queue's access policy to allow the Amazon SNS topic to send messages. Example policy statement: { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:us-east-1:111122223333:MyQueue", "Condition": { "ArnEquals": { "aws:SourceArn": "arn:aws:sns:us-east-1:123456789012:MyTopic" } } } This policy allows MyTopic to send messages to MyQueue. Cross-account subscriptions 118 Amazon Simple Queue Service Developer Guide Cross-region subscriptions To subscribe to an Amazon SNS topic in a different AWS Region, ensure that: • The Amazon SNS topic's access policy allows cross-region subscriptions. • The Amazon SQS queue's access policy permits the Amazon SNS topic to send messages across regions. For more information, Sending Amazon SNS messages to an Amazon SQS queue or AWS Lambda function in a different Region in the Amazon Simple Notification Service Developer Guide. Configuring an Amazon SQS queue to trigger an AWS Lambda function You can use a Lambda function to process messages from an Amazon SQS queue. Lambda polls the queue and invokes your function synchronously, passing a batch of messages as an event. Configuring visibility timeout Set the queue's visibility timeout to at least six times the function timeout. This ensures Lambda has enough time to retry if a function is throttled while processing a previous batch. Using a dead-letter queue (DLQ) Specify a dead-letter queue to capture messages that the Lambda function fails to process. Handling multiple queues and functions A Lambda function can process multiple queues by creating a separate event source for each queue. You can also associate multiple Lambda functions with the same queue. Permissions for encrypted queues If you associate an encrypted queue with a Lambda function but Lambda doesn't poll for messages, add the kms:Decrypt permission to your Lambda execution role. Restrictions The queue and Lambda function must be in the same AWS Region. An encrypted queue that uses the default key (AWS managed KMS key for Amazon SQS) cannot invoke a Lambda function in a different AWS account. Cross-region subscriptions 119 Amazon Simple Queue Service Developer Guide For implementation details, see Using AWS Lambda with Amazon SQS in the AWS Lambda Developer Guide. Prerequisites To configure Lambda function triggers, you must meet the following requirements: • If you use a user, your Amazon SQS role must include the following permissions: • lambda:CreateEventSourceMapping • lambda:ListEventSourceMappings • lambda:ListFunctions • The Lambda execution role must include the following permissions: • sqs:DeleteMessage • sqs:GetQueueAttributes • sqs:ReceiveMessage • If you associate an encrypted queue with a Lambda function, add the kms:Decrypt permission to
|
sqs-dg-044
|
sqs-dg.pdf
| 44 |
cannot invoke a Lambda function in a different AWS account. Cross-region subscriptions 119 Amazon Simple Queue Service Developer Guide For implementation details, see Using AWS Lambda with Amazon SQS in the AWS Lambda Developer Guide. Prerequisites To configure Lambda function triggers, you must meet the following requirements: • If you use a user, your Amazon SQS role must include the following permissions: • lambda:CreateEventSourceMapping • lambda:ListEventSourceMappings • lambda:ListFunctions • The Lambda execution role must include the following permissions: • sqs:DeleteMessage • sqs:GetQueueAttributes • sqs:ReceiveMessage • If you associate an encrypted queue with a Lambda function, add the kms:Decrypt permission to the Lambda execution role. For more information, see Overview of managing access in Amazon SQS. To configure a queue to trigger a Lambda function (console) 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. On the Queues page, choose the queue to configure. 4. On the queue's page, choose the Lambda triggers tab. 5. On the Lambda triggers page, choose a Lambda trigger. If the list doesn't include the Lambda trigger that you need, choose Configure Lambda function trigger. Enter the Amazon Resource Name (ARN) of the Lambda function or choose an existing resource. Then choose Save. 6. Choose Save. The console saves the configuration and displays the Details page for the queue. On the Details page, the Lambda triggers tab displays the Lambda function and its status. It takes approximately 1 minute for the Lambda function to become associated with your queue. Prerequisites 120 Amazon Simple Queue Service Developer Guide 7. To verify the results of the configuration, send a message to your queue and then view the triggered Lambda function in the Lambda console. Automating notifications from AWS services to Amazon SQS using Amazon EventBridge Amazon EventBridge allows you to automate AWS services and respond to events, such as application issues or resource changes, in near real-time. • You can create rules to filter specific events and define automated actions when a rule matches an event. • EventBridge supports multiple targets, including Amazon SQS standard and FIFO queues, which receive events in JSON format. For more information, see Amazon EventBridge targets in the Amazon EventBridge User Guide. Sending a message with attributes using Amazon SQS For standard and FIFO queues, you can include structured metadata to messages, including timestamps, geospatial data, signatures, and identifiers . For more information, see Amazon SQS message attributes. To send a message with attributes to a queue using the Amazon SQS console 1. Open the Amazon SQS console at https://console.aws.amazon.com/sqs/. 2. In the navigation pane, choose Queues. 3. On the Queues page, choose a queue. 4. Choose Send and receive messages. 5. Enter the message attribute parameters. a. b. c. In the name text box, enter a unique name of up to 256 characters. For the attribute type, choose String, Number, or Binary. (Optional) Enter a custom data type. For example, you could add byte, int, or float as custom data types for Number. d. In the value text box, enter the message attribute value. Automating notifications using EventBridge 121 Amazon Simple Queue Service Developer Guide 6. To add another message attribute., choose Add new attribute. 7. You can modify the attribute values any time before sending the message. 8. To delete an attribute, choose Remove. To delete the first attribute, close Message attributes. 9. When you finish adding attributes to the message, choose Send message. Your message is sent and the console displays a success message. To view information about the message attributes of the sent message, choose View details. Choose Done to close the Message details dialog box. Message attributes 122 Amazon Simple Queue Service Developer Guide Amazon SQS best practices Amazon SQS manages and processes message queues, enabling different parts of an application to exchange messages reliably and at scale. This topic covers key operational best practices, including using long polling to reduce empty responses, implementing dead-letter queues to handle processing errors, and optimizing queue permissions for security. Topics • Amazon SQS error handling and problematic messages • Amazon SQS message deduplication and grouping • Amazon SQS message processing and timing Amazon SQS error handling and problematic messages This topic provides detailed instructions on managing and mitigating errors in Amazon SQS, including techniques for handling request errors, capturing problematic messages, and configuring dead-letter queue retention to ensure message reliability. Topics • Handling request errors in Amazon SQS • Capturing problematic messages in Amazon SQS • Setting-up dead-letter queue retention in Amazon SQS Handling request errors in Amazon SQS To handle request errors, use one of the following strategies: • If you use an AWS SDK, you already have automatic retry and backoff logic at your disposal. For more information, see Error Retries and Exponential Backoff in AWS in the Amazon Web Services General
|
sqs-dg-045
|
sqs-dg.pdf
| 45 |
on managing and mitigating errors in Amazon SQS, including techniques for handling request errors, capturing problematic messages, and configuring dead-letter queue retention to ensure message reliability. Topics • Handling request errors in Amazon SQS • Capturing problematic messages in Amazon SQS • Setting-up dead-letter queue retention in Amazon SQS Handling request errors in Amazon SQS To handle request errors, use one of the following strategies: • If you use an AWS SDK, you already have automatic retry and backoff logic at your disposal. For more information, see Error Retries and Exponential Backoff in AWS in the Amazon Web Services General Reference. • If you don't use the AWS SDK features for retry and backoff, allow a pause (for example, 200 ms) before retrying the ReceiveMessage action after receiving no messages, a timeout, or an error message from Amazon SQS. For subsequent use of ReceiveMessage that gives the same results, allow a longer pause (for example, 400 ms). Error handling and problematic messages 123 Amazon Simple Queue Service Developer Guide Capturing problematic messages in Amazon SQS To capture all messages that can't be processed, and to collect accurate CloudWatch metrics, configure a dead-letter queue. • The redrive policy redirects messages to a dead-letter queue after the source queue fails to process a message a specified number of times. • Using a dead-letter queue decreases the number of messages and reduces the possibility of exposing you to poison pill messages (messages that are received but can't be processed). • Including a poison pill message in a queue can distort the ApproximateAgeOfOldestMessage CloudWatch metric by giving an incorrect age of the poison pill message. Configuring a dead- letter queue helps avoid false alarms when using this metric. Setting-up dead-letter queue retention in Amazon SQS For standard queues, the expiration of a message is always based on its original enqueue timestamp. When a message is moved to a dead-letter queue, the enqueue timestamp is unchanged. The ApproximateAgeOfOldestMessage metric indicates when the message moved to the dead-letter queue, not when the message was originally sent. For example, assume that a message spends 1 day in the original queue before it's moved to a dead-letter queue. If the dead-letter queue's retention period is 4 days, the message is deleted from the dead-letter queue after 3 days and the ApproximateAgeOfOldestMessage is 3 days. Thus, it is a best practice to always set the retention period of a dead-letter queue to be longer than the retention period of the original queue. For FIFO queues, the enqueue timestamp resets when the message is moved to a dead-letter queue. The ApproximateAgeOfOldestMessage metric indicates when the message moved to the dead-letter queue. In the same example above, the message is deleted from the dead-letter queue after 4 days and the ApproximateAgeOfOldestMessage is 4 days. Amazon SQS message deduplication and grouping This topic provides best practices for ensuring consistent message processing in Amazon SQS. It explains how to use: • MessageDeduplicationId to prevent duplicate messages in FIFO queues. • MessageGroupId to manage message ordering within distinct message groups. Capturing problematic messages in Amazon SQS 124 Amazon Simple Queue Service Topics • Avoiding inconsistent message processing in Amazon SQS • Using the message deduplication ID in Amazon SQS • Using the Amazon SQS message group ID • Using the Amazon SQS receive request attempt ID Developer Guide Avoiding inconsistent message processing in Amazon SQS Because Amazon SQS is a distributed system, it is possible for a consumer to not receive a message even when Amazon SQS marks the message as delivered while returning successfully from a ReceiveMessage API method call. In this case, Amazon SQS records the message as delivered at least once, although the consumer has never received it. Because no additional attempts to deliver messages are made under these conditions, we don't recommend setting the number of maximum receives to 1 for a dead-letter queue. Using the message deduplication ID in Amazon SQS MessageDeduplicationId is a token used only in Amazon SQS FIFO queues to prevent duplicate message delivery. It ensures that within a 5-minute deduplication window, only one instance of a message with the same deduplication ID is processed and delivered. If Amazon SQS has already accepted a message with a specific deduplication ID, any subsequent messages with the same ID will be acknowledged but not delivered to consumers. Note Amazon SQS continues tracking the deduplication ID even after the message has been received and deleted. Topics • When to provide a message deduplication ID in Amazon SQS • Enabling deduplication for a single-producer/consumer system in Amazon SQS • Outage recovery scenarios in Amazon SQS • Configuring visibility timeouts in Amazon SQS Avoiding inconsistent message processing in Amazon SQS 125 Amazon Simple Queue Service Developer Guide When to provide a message deduplication ID in Amazon SQS A producer should specify
|
sqs-dg-046
|
sqs-dg.pdf
| 46 |
a specific deduplication ID, any subsequent messages with the same ID will be acknowledged but not delivered to consumers. Note Amazon SQS continues tracking the deduplication ID even after the message has been received and deleted. Topics • When to provide a message deduplication ID in Amazon SQS • Enabling deduplication for a single-producer/consumer system in Amazon SQS • Outage recovery scenarios in Amazon SQS • Configuring visibility timeouts in Amazon SQS Avoiding inconsistent message processing in Amazon SQS 125 Amazon Simple Queue Service Developer Guide When to provide a message deduplication ID in Amazon SQS A producer should specify a message deduplication ID in the following scenarios: • When sending identical message bodies that must be treated as unique. • When sending messages with the same content but different message attributes, ensuring each message is processed separately. • When sending messages with different content (for example, a retry counter in the message body) but requiring Amazon SQS to recognize them as duplicates. Enabling deduplication for a single-producer/consumer system in Amazon SQS If you have a single producer and a single consumer, and messages are unique because they include an application-specific message ID in the body, follow these best practices: • Enable content-based deduplication for the queue (each of your messages has a unique body). The producer can omit the message deduplication ID. • When content-based deduplication is enabled for an Amazon SQS FIFO queue, and a message is sent with a deduplication ID, the SendMessage deduplication ID overrides the generated content-based deduplication ID. • Although the consumer isn't required to provide a receive request attempt ID for each request, it's a best practice because it allows fail-retry sequences to execute faster. • You can retry send or receive requests because they don't interfere with the ordering of messages in FIFO queues. Outage recovery scenarios in Amazon SQS The deduplication process in FIFO queues is time-sensitive. When designing your application, ensure that both the producer and consumer can recover from client or network outages without introducing duplicates or processing failures. Producer considerations • Amazon SQS enforces a 5-minute deduplication window. • If a producer retries a SendMessage request after 5-minutes, Amazon SQS treats it as a new message, potentially creating duplicates. Using the message deduplication ID 126 Amazon Simple Queue Service Consumer considerations Developer Guide • If a consumer fails to process a message before the visibility timeout expires, another consumer may receive and process it, leading to duplicate processing. • Adjust the visibility timeout based on your application's processing time. • Use the ChangeMessageVisibility API to extend the timeout while a message is still being processed. • If a message repeatedly fails to process, route it to a dead-letter queue (DLQ) instead of allowing it to be reprocessed indefinitely. • The producer must be aware of the deduplication interval of the queue. Amazon SQS has a deduplication interval of 5 minutes. Retrying SendMessage requests after the deduplication interval expires can introduce duplicate messages into the queue. For example, a mobile device in a car sends messages whose order is important. If the car loses cellular connectivity for a period of time before receiving an acknowledgement, retrying the request after regaining cellular connectivity can create a duplicate. • The consumer must have a visibility timeout that minimizes the risk of being unable to process messages before the visibility timeout expires. You can extend the visibility timeout while the messages are being processed by calling the ChangeMessageVisibility action. However, if the visibility timeout expires, another consumer can immediately begin to process the messages, causing a message to be processed multiple times. To avoid this scenario, configure a dead-letter queue. Configuring visibility timeouts in Amazon SQS To ensure reliable message processing, set the visibility timeout to be longer than the AWS SDK read timeout. This applies when using the ReceiveMessage API with both short polling and long polling. A longer visibility timeout prevents messages from becoming available to other consumers before the original request completes, reducing the risk of duplicate processing. Using the Amazon SQS message group ID MessageGroupId is an attribute used only in Amazon SQS FIFO (First-In-First-Out) queues to organize messages into distinct groups. Messages within the same message group are always processed one at a time, in strict order, ensuring that no two messages from the same group are Using the message group ID 127 Amazon Simple Queue Service Developer Guide processed simultaneously. Standard queues do not use MessageGroupId and do not provide ordering guarantees. If strict ordering is required, use a FIFO queue instead. Topics • Interleaving multiple ordered message groups in Amazon SQS • Preventing duplicate processing in a multiple-producer/consumer system in Amazon SQS • Avoid large message backlogs with the same message group ID in Amazon SQS • Avoid reusing the same message group ID with
|
sqs-dg-047
|
sqs-dg.pdf
| 47 |
are always processed one at a time, in strict order, ensuring that no two messages from the same group are Using the message group ID 127 Amazon Simple Queue Service Developer Guide processed simultaneously. Standard queues do not use MessageGroupId and do not provide ordering guarantees. If strict ordering is required, use a FIFO queue instead. Topics • Interleaving multiple ordered message groups in Amazon SQS • Preventing duplicate processing in a multiple-producer/consumer system in Amazon SQS • Avoid large message backlogs with the same message group ID in Amazon SQS • Avoid reusing the same message group ID with virtual queues in Amazon SQS Interleaving multiple ordered message groups in Amazon SQS To interleave multiple ordered message groups within a single FIFO queue, assign a MessageGroupId to each group (for example, session data for different users). This allows multiple consumers to read from the queue simultaneously while ensuring that messages within the same group are processed in order. When a message with a specific MessageGroupId is being processed and is invisible, no other consumer can process messages from that same group until the visibility timeout expires or the message is deleted. Preventing duplicate processing in a multiple-producer/consumer system in Amazon SQS In a high-throughput, low-latency system where message ordering is not a priority, producers can assign a unique MessageGroupId to each message. This ensures that Amazon SQS FIFO queues eliminate duplicates, even in a multiple-producer/multiple-consumer setup. While this approach prevents duplicate messages, it does not guarantee message ordering since each message is treated as its own independent group. In any system with multiple producers and consumers, there is always a risk of duplicate delivery. If a consumer fails to process a message before the visibility timeout expires, Amazon SQS makes the message available again, potentially allowing another consumer to pick it up. To mitigate this, ensure proper message acknowledgment and visibility timeout settings based on processing time. Using the message group ID 128 Amazon Simple Queue Service Developer Guide Avoid large message backlogs with the same message group ID in Amazon SQS FIFO queues support a maximum of 120,000 in-flight messages (messages received by a consumer but not yet deleted). If this limit is reached, Amazon SQS does not return an error, but processing may be impacted. You can request an increase beyond this limit by contacting AWS Support. FIFO queues scan the first 120,000 messages to determine available message groups. If a large backlog builds up in a single message group, messages from other groups sent later will remain blocked until the backlog is processed. Note A message backlog can occur when a consumer repeatedly fails to process a message. This could be due to message content issues or consumer-side failures. To prevent message processing delays, configure a dead-letter queue to move unprocessed messages after multiple failed attempts. This ensures that other messages in the same message group can be processed, preventing system bottlenecks. Avoid reusing the same message group ID with virtual queues in Amazon SQS When using virtual queues with a shared host queue, avoid reusing the same MessageGroupId across different virtual queues. If multiple virtual queues share the same host queue and contain messages with the same MessageGroupId, those messages can block each other, preventing efficient processing. To ensure smooth message processing, assign unique MessageGroupId values for messages in different virtual queues. Using the Amazon SQS receive request attempt ID The receive request attempt ID is a unique token used to deduplicate ReceiveMessage calls in Amazon SQS. During a network outage or connectivity issue between your application and Amazon SQS, it is best practice to: • Provide a receive request attempt ID when making a ReceiveMessage call. • Retry using the same receive request attempt ID if the operation fails. Using the receive request attempt ID 129 Amazon Simple Queue Service Developer Guide Amazon SQS message processing and timing This topic provides a comprehensive guidance on optimizing the speed and efficiency of message handling in Amazon SQS, including strategies for timely message processing, selecting the best polling mode, and configuring long polling for improved performance. Topics • Processing messages in a timely manner in Amazon SQS • Setting-up long polling in Amazon SQS • Using the appropriate polling mode in Amazon SQS Processing messages in a timely manner in Amazon SQS Setting the visibility timeout depends on how long it takes your application to process and delete a message. For example, if your application requires 10 seconds to process a message and you set the visibility timeout to 15 minutes, you must wait for a relatively long time to attempt to process the message again if the previous processing attempt fails. Alternatively, if your application requires 10 seconds to process a message but you set the visibility timeout to only 2 seconds, a duplicate message
|
sqs-dg-048
|
sqs-dg.pdf
| 48 |
the appropriate polling mode in Amazon SQS Processing messages in a timely manner in Amazon SQS Setting the visibility timeout depends on how long it takes your application to process and delete a message. For example, if your application requires 10 seconds to process a message and you set the visibility timeout to 15 minutes, you must wait for a relatively long time to attempt to process the message again if the previous processing attempt fails. Alternatively, if your application requires 10 seconds to process a message but you set the visibility timeout to only 2 seconds, a duplicate message is received by another consumer while the original consumer is still working on the message. To make sure that there is sufficient time to process messages, use one of the following strategies: • If you know (or can reasonably estimate) how long it takes to process a message, extend the message's visibility timeout to the maximum time it takes to process and delete the message. For more information, see Configuring the Visibility Timeout. • If you don't know how long it takes to process a message, create a heartbeat for your consumer process: Specify the initial visibility timeout (for example, 2 minutes) and then—as long as your consumer still works on the message—keep extending the visibility timeout by 2 minutes every minute. Important The maximum visibility timeout is 12 hours from the time that Amazon SQS receives the ReceiveMessage request. Extending the visibility timeout does not reset the 12 hour maximum. Message processing and timing 130 Amazon Simple Queue Service Developer Guide Additionally, you may be unable to set the timeout on an individual message to the full 12 hours (e.g. 43,200 seconds) since the ReceiveMessage request initiates the timer. For example, if you receive a message and immediately set the 12 hour maximum by sending a ChangeMessageVisibility call with VisibilityTimeout equal to 43,200 seconds, it will likely fail. However, using a value of 43,195 seconds will work unless there is a significant delay between requesting the message via ReceiveMessage and updating the visibility timeout. If your consumer needs longer than 12 hours, consider using Step Functions. Setting-up long polling in Amazon SQS When the wait time for the ReceiveMessage API action is greater than 0, long polling is in effect. The maximum long polling wait time is 20 seconds. Long polling helps reduce the cost of using Amazon SQS by eliminating the number of empty responses (when there are no messages available for a ReceiveMessage request) and false empty responses (when messages are available but aren't included in a response). For more information, see Amazon SQS short and long polling. For optimal message processing, use the following strategies: • In most cases, you can set the ReceiveMessage wait time to 20 seconds. If 20 seconds is too long for your application, set a shorter ReceiveMessage wait time (1 second minimum). If you don't use an AWS SDK to access Amazon SQS, or if you configure an AWS SDK to have a shorter wait time, you might have to modify your Amazon SQS client to either allow longer requests or use a shorter wait time for long polling. • If you implement long polling for multiple queues, use one thread for each queue instead of a single thread for all queues. Using a single thread for each queue allows your application to process the messages in each of the queues as they become available, while using a single thread for polling multiple queues might cause your application to become unable to process messages available in other queues while the application waits (up to 20 seconds) for the queue which doesn't have any available messages. Setting-up long polling in Amazon SQS 131 Amazon Simple Queue Service Developer Guide Important To avoid HTTP errors, make sure that the HTTP response timeout for ReceiveMessage requests is longer than the WaitTimeSeconds parameter. For more information, see ReceiveMessage. Using the appropriate polling mode in Amazon SQS • Long polling lets you consume messages from your Amazon SQS queue as soon as they become available. • To reduce the cost of using Amazon SQS and to decrease the number of empty receives to an empty queue (responses to the ReceiveMessage action which return no messages), enable long polling. For more information, see Amazon SQS Long Polling. • To increase efficiency when polling for multiple threads with multiple receives, decrease the number of threads. • Long polling is preferable over short polling in most cases. • Short polling returns responses immediately, even if the polled Amazon SQS queue is empty. • To satisfy the requirements of an application that expects immediate responses to the ReceiveMessage request, use short polling. • Short polling is billed the same as long polling. Using the appropriate polling mode in Amazon SQS
|
sqs-dg-049
|
sqs-dg.pdf
| 49 |
(responses to the ReceiveMessage action which return no messages), enable long polling. For more information, see Amazon SQS Long Polling. • To increase efficiency when polling for multiple threads with multiple receives, decrease the number of threads. • Long polling is preferable over short polling in most cases. • Short polling returns responses immediately, even if the polled Amazon SQS queue is empty. • To satisfy the requirements of an application that expects immediate responses to the ReceiveMessage request, use short polling. • Short polling is billed the same as long polling. Using the appropriate polling mode in Amazon SQS 132 Amazon Simple Queue Service Developer Guide Amazon SQS Java SDK examples The AWS SDK for Java allows you build Java applications that interact with Amazon SQS and other AWS services. • To install and set up the SDK, see Getting started in the AWS SDK for Java 2.x Developer Guide. • For basic queue operations—such as creating a queue or sending a message—see Working with Amazon SQS Message Queues in the AWS SDK for Java 2.x Developer Guide. • This guide also includes examples of additional Amazon SQS features, such as: • Using server-side encryption with Amazon SQS queues • Configuring tags for an Amazon SQS queue • Sending message attributes to an Amazon SQS queue Using server-side encryption with Amazon SQS queues Use the AWS SDK for Java to add server-side encryption (SSE) to an Amazon SQS queue. Each queue uses an AWS Key Management Service (AWS KMS) KMS key to generate the data encryption keys. This example uses the AWS managed KMS key for Amazon SQS. For more information about using SSE and the role of the KMS key, see Encryption at rest in Amazon SQS. Adding SSE to an existing queue To enable server-side encryption for an existing queue, use the SetQueueAttributes method to set the KmsMasterKeyId attribute. The following code example sets the AWS KMS key as the AWS managed KMS key for Amazon SQS. The example also sets the AWS KMS key reuse period to 140 seconds. Before you run the example code, make sure that you have set your AWS credentials. For more information, see Set up AWS Credentials and Region for Development in the AWS SDK for Java 2.x Developer Guide. public static void addEncryption(String queueName, String kmsMasterKeyAlias) { Using server-side encryption 133 Amazon Simple Queue Service Developer Guide SqsClient sqsClient = SqsClient.create(); GetQueueUrlRequest urlRequest = GetQueueUrlRequest.builder() .queueName(queueName) .build(); GetQueueUrlResponse getQueueUrlResponse; try { getQueueUrlResponse = sqsClient.getQueueUrl(urlRequest); } catch (QueueDoesNotExistException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } String queueUrl = getQueueUrlResponse.queueUrl(); Map<QueueAttributeName, String> attributes = Map.of( QueueAttributeName.KMS_MASTER_KEY_ID, kmsMasterKeyAlias, QueueAttributeName.KMS_DATA_KEY_REUSE_PERIOD_SECONDS, "140" // Set the data key reuse period to 140 seconds. ); // This is how long SQS can reuse the data key before requesting a new one from KMS. SetQueueAttributesRequest attRequest = SetQueueAttributesRequest.builder() .queueUrl(queueUrl) .attributes(attributes) .build(); try { sqsClient.setQueueAttributes(attRequest); LOGGER.info("The attributes have been applied to {}", queueName); } catch (InvalidAttributeNameException | InvalidAttributeValueException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } finally { sqsClient.close(); } } Disabling SSE for a queue To disable server-side encryption for an existing queue, set the KmsMasterKeyId attribute to an empty string using the SetQueueAttributes method. Disabling SSE for a queue 134 Amazon Simple Queue Service Developer Guide Important null isn't a valid value for KmsMasterKeyId. Creating a queue with SSE To enable SSE when you create the queue, add the KmsMasterKeyId attribute to the CreateQueue API method. The following example creates a new queue with SSE enabled. The queue uses the AWS managed KMS key for Amazon SQS. The example also sets the AWS KMS key reuse period to 160 seconds. Before you run the example code, make sure that you have set your AWS credentials. For more information, see Set up AWS Credentials and Region for Development in the AWS SDK for Java 2.x Developer Guide. // Create an SqsClient for the specified Region. SqsClient sqsClient = SqsClient.builder().region(Region.US_WEST_1).build(); // Create a hashmap for the attributes. Add the key alias and reuse period to the hashmap. HashMap<QueueAttributeName, String> attributes = new HashMap<QueueAttributeName, String>(); final String kmsMasterKeyAlias = "alias/aws/sqs"; // the alias of the AWS managed KMS key for Amazon SQS. attributes.put(QueueAttributeName.KMS_MASTER_KEY_ID, kmsMasterKeyAlias); attributes.put(QueueAttributeName.KMS_DATA_KEY_REUSE_PERIOD_SECONDS, "140"); // Add the attributes to the CreateQueueRequest. CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .attributes(attributes) .build(); sqsClient.createQueue(createQueueRequest); Creating a queue with SSE 135 Amazon Simple Queue Service Developer Guide Retrieving SSE attributes For information about retrieving queue attributes, see Examples in the Amazon Simple Queue Service API Reference. To retrieve the KMS key ID or the data key reuse period for a particular queue, run the GetQueueAttributes method and retrieve the KmsMasterKeyId and KmsDataKeyReusePeriodSeconds values. Configuring tags for an Amazon SQS queue Use cost-allocation tags to help organize and identify your Amazon SQS queues. The following examples show how to configure tags using the AWS
|
sqs-dg-050
|
sqs-dg.pdf
| 50 |
attributes to the CreateQueueRequest. CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .attributes(attributes) .build(); sqsClient.createQueue(createQueueRequest); Creating a queue with SSE 135 Amazon Simple Queue Service Developer Guide Retrieving SSE attributes For information about retrieving queue attributes, see Examples in the Amazon Simple Queue Service API Reference. To retrieve the KMS key ID or the data key reuse period for a particular queue, run the GetQueueAttributes method and retrieve the KmsMasterKeyId and KmsDataKeyReusePeriodSeconds values. Configuring tags for an Amazon SQS queue Use cost-allocation tags to help organize and identify your Amazon SQS queues. The following examples show how to configure tags using the AWS SDK for Java. For more information, see Amazon SQS cost allocation tags. Before you run the example code, make sure that you have set your AWS credentials. For more information, see Set up AWS Credentials and Region for Development in the AWS SDK for Java 2.x Developer Guide. Listing tags To list the tags for a queue, use the ListQueueTags method. // Create an SqsClient for the specified region. SqsClient sqsClient = SqsClient.builder().region(Region.US_WEST_1).build(); // Get the queue URL. String queueName = "MyStandardQ1"; GetQueueUrlResponse getQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()); String queueUrl = getQueueUrlResponse.queueUrl(); // Create the ListQueueTagsRequest. final ListQueueTagsRequest listQueueTagsRequest = ListQueueTagsRequest.builder().queueUrl(queueUrl).build(); // Retrieve the list of queue tags and print them. final ListQueueTagsResponse listQueueTagsResponse = sqsClient.listQueueTags(listQueueTagsRequest); Retrieving SSE attributes 136 Amazon Simple Queue Service Developer Guide System.out.println(String.format("ListQueueTags: \tTags for queue %s are %s.\n", queueName, listQueueTagsResponse.tags() )); Adding or updating tags To add or update tag values for a queue, use the TagQueue method. // Create an SqsClient for the specified Region. SqsClient sqsClient = SqsClient.builder().region(Region.US_WEST_1).build(); // Get the queue URL. String queueName = "MyStandardQ1"; GetQueueUrlResponse getQueueUrlResponse = sqsClient.getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()); String queueUrl = getQueueUrlResponse.queueUrl(); // Build a hashmap of the tags. final HashMap<String, String> addedTags = new HashMap<>(); addedTags.put("Team", "Development"); addedTags.put("Priority", "Beta"); addedTags.put("Accounting ID", "456def"); //Create the TagQueueRequest and add them to the queue. final TagQueueRequest tagQueueRequest = TagQueueRequest.builder() .queueUrl(queueUrl) .tags(addedTags) .build(); sqsClient.tagQueue(tagQueueRequest); Removing tags To remove one or more tags from the queue, use the UntagQueue method. The following example removes the Accounting ID tag. // Create the UntagQueueRequest. final UntagQueueRequest untagQueueRequest = UntagQueueRequest.builder() .queueUrl(queueUrl) .tagKeys("Accounting ID") Adding or updating tags 137 Amazon Simple Queue Service .build(); // Remove the tag from this queue. sqsClient.untagQueue(untagQueueRequest); Developer Guide Sending message attributes to an Amazon SQS queue You can include structured metadata (such as timestamps, geospatial data, signatures, and identifiers) with messages using message attributes. For more information, see Amazon SQS message attributes. Before you run the example code, make sure that you have set your AWS credentials. For more information, see Set up AWS Credentials and Region for Development in the AWS SDK for Java 2.x Developer Guide. Defining attributes To define an attribute for a message, add the following code, which uses the MessageAttributeValue data type. For more information, see Message attribute components and Message attribute data types. The AWS SDK for Java automatically calculates the message body and message attribute checksums and compares them with the data that Amazon SQS returns. For more information, see the AWS SDK for Java 2.x Developer Guide and Calculating the MD5 message digest for message attributes for other programming languages. String This example defines a String attribute named Name with the value Jane. final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("Name", new MessageAttributeValue() .withDataType("String") .withStringValue("Jane")); Number This example defines a Number attribute named AccurateWeight with the value 230.000000000000000001. Sending message attributes 138 Amazon Simple Queue Service Developer Guide final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("AccurateWeight", new MessageAttributeValue() .withDataType("Number") .withStringValue("230.000000000000000001")); Binary This example defines a Binary attribute named ByteArray with the value of an uninitialized 10-byte array. final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("ByteArray", new MessageAttributeValue() .withDataType("Binary") .withBinaryValue(ByteBuffer.wrap(new byte[10]))); String (custom) This example defines the custom attribute String.EmployeeId named EmployeeId with the value ABC123456. final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("EmployeeId", new MessageAttributeValue() .withDataType("String.EmployeeId") .withStringValue("ABC123456")); Number (custom) This example defines the custom attribute Number.AccountId named AccountId with the value 000123456. final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("AccountId", new MessageAttributeValue() .withDataType("Number.AccountId") .withStringValue("000123456")); Note Because the base data type is Number, the ReceiveMessage method returns 123456. Defining attributes 139 Amazon Simple Queue Service Binary (custom) Developer Guide This example defines the custom attribute Binary.JPEG named ApplicationIcon with the value of an uninitialized 10-byte array. final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("ApplicationIcon", new MessageAttributeValue() .withDataType("Binary.JPEG") .withBinaryValue(ByteBuffer.wrap(new byte[10]))); Sending a message with attributes This example adds the attributes to the SendMessageRequest before sending the message. // Send a message with an attribute. final SendMessageRequest sendMessageRequest = new SendMessageRequest(); sendMessageRequest.withMessageBody("This is my message text."); sendMessageRequest.withQueueUrl(myQueueUrl); sendMessageRequest.withMessageAttributes(messageAttributes); sqs.sendMessage(sendMessageRequest); Important If you send a message to a First-In-First-Out (FIFO) queue, make sure that the sendMessage method executes after you provide the message group ID. If you use the SendMessageBatch method instead of SendMessage, you must specify message attributes for
|
sqs-dg-051
|
sqs-dg.pdf
| 51 |
ApplicationIcon with the value of an uninitialized 10-byte array. final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put("ApplicationIcon", new MessageAttributeValue() .withDataType("Binary.JPEG") .withBinaryValue(ByteBuffer.wrap(new byte[10]))); Sending a message with attributes This example adds the attributes to the SendMessageRequest before sending the message. // Send a message with an attribute. final SendMessageRequest sendMessageRequest = new SendMessageRequest(); sendMessageRequest.withMessageBody("This is my message text."); sendMessageRequest.withQueueUrl(myQueueUrl); sendMessageRequest.withMessageAttributes(messageAttributes); sqs.sendMessage(sendMessageRequest); Important If you send a message to a First-In-First-Out (FIFO) queue, make sure that the sendMessage method executes after you provide the message group ID. If you use the SendMessageBatch method instead of SendMessage, you must specify message attributes for each message in the batch. Sending a message with attributes 140 Amazon Simple Queue Service Developer Guide Using APIs with Amazon SQS This topic provides information about constructing Amazon SQS endpoints, making query API requests using the GET and POST methods, and using batch API actions. For detailed information about Amazon SQS actions—including parameters, errors, examples, and data types, see the Amazon Simple Queue Service API Reference. To access Amazon SQS using a variety of programming languages, you can also use AWS SDKs, which contain the following automatic functionality: • Cryptographically signing your service requests • Retrying requests • Handling error responses For more information, see the section called “Working with AWS SDKs”. For command line tool information, see the Amazon SQS sections in the AWS CLI Command Reference and the AWS Tools for PowerShell Cmdlet Reference. Amazon SQS APIs with AWS JSON protocol Amazon SQS uses AWS JSON protocol as the transport mechanism for all Amazon SQS APIs on the specified AWS SDK versions. AWS JSON protocol provides a higher throughput, lower latency, and faster application-to-application communication. AWS JSON protocol is more efficient in serialization/deserialization of requests and responses when compared to AWS query protocol. If you still prefer to use the AWS query protocol with SQS APIs, see What languages are supported for AWS JSON protocol used in Amazon SQS APIs? for the AWS SDK versions that support Amazon SQS AWS query protocol. Amazon SQS uses AWS JSON protocol to communicate between AWS SDK clients (for example, Java, Python, Golang, JavaScript) and the Amazon SQS server. An HTTP request of an Amazon SQS API operation accepts JSON formatted input. The Amazon SQS operation is executed, and the execution response is sent back to the SDK client in JSON format. Compared to AWS query, AWS JSON is simpler, faster, and more efficient to transport data between client and server. • AWS JSON protocol acts as a mediator between the Amazon SQS client and server. • The server doesn’t understand the programming language in which the Amazon SQS operation is created, but it understands the AWS JSON protocol. 141 Amazon Simple Queue Service Developer Guide • The AWS JSON protocol uses the serialization (convert object to JSON format) and de- serialization (convert JSON format to object) between Amazon SQS client and server. For more information about AWS JSON protocol with Amazon SQS, see Amazon SQS AWS JSON protocol FAQs. AWS JSON protocol is available on the specified AWS SDK version. To review SDK version and release dates across language variants, see the AWS SDKs and Tools version support matrix in the AWS SDKs and Tools Reference Guide Making query API requests using AWS JSON protocol in Amazon SQS This topic explains how to construct an Amazon SQS endpoint, make POST requests, and interpret responses. Note AWS JSON protocol is supported for most language variants. For a full list of supported language variants, see What languages are supported for AWS JSON protocol used in Amazon SQS APIs?. Constructing an endpoint To work with Amazon SQS queues, you must construct an endpoint. For information about Amazon SQS endpoints, see the following pages in the Amazon Web Services General Reference: • Regional endpoints • Amazon Simple Queue Service endpoints and quotas Every Amazon SQS endpoint is independent. For example, if two queues are named MyQueue and one has the endpoint sqs.us-east-2.amazonaws.com while the other has the endpoint sqs.eu-west-2.amazonaws.com, the two queues don't share any data with each other. The following is an example of an endpoint that makes a request to create a queue. Making query API requests using AWS JSON protocol 142 Amazon Simple Queue Service Developer Guide POST / HTTP/1.1 Host: sqs.us-west-2.amazonaws.com X-Amz-Target: AmazonSQS.CreateQueue X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueName":"MyQueue", "Attributes": { "VisibilityTimeout": "40" }, "tags": { "QueueType": "Production" } } Note Queue names and queue URLs are case sensitive. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Signing AWS API Requests in the Amazon Web Services General Reference. Making a POST request An Amazon SQS POST request sends query parameters as a form in the body of an HTTP request. The following is an example of
|
sqs-dg-052
|
sqs-dg.pdf
| 52 |
Amazon Simple Queue Service Developer Guide POST / HTTP/1.1 Host: sqs.us-west-2.amazonaws.com X-Amz-Target: AmazonSQS.CreateQueue X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive { "QueueName":"MyQueue", "Attributes": { "VisibilityTimeout": "40" }, "tags": { "QueueType": "Production" } } Note Queue names and queue URLs are case sensitive. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Signing AWS API Requests in the Amazon Web Services General Reference. Making a POST request An Amazon SQS POST request sends query parameters as a form in the body of an HTTP request. The following is an example of an HTTP header with X-Amz-Target set to AmazonSQS.<operationName>, and an HTTP header with Content-Type set to application/ x-amz-json-1.0. POST / HTTP/1.1 Host: sqs.<region>.<domain> X-Amz-Target: AmazonSQS.SendMessage X-Amz-Date: <Date> Content-Type: application/x-amz-json-1.0 Authorization: <AuthParams> Content-Length: <PayloadSizeBytes> Connection: Keep-Alive Making a POST request 143 Amazon Simple Queue Service { Developer Guide "QueueUrl": "https://sqs.<region>.<domain>/<awsAccountId>/<queueName>/", "MessageBody": "This is a test message" } This HTTP POST request sends a message to an Amazon SQS queue. Note Both HTTP headers X-Amz-Target and Content-Type are required. Your HTTP client might add other items to the HTTP request, according to the client's HTTP version. Interpreting Amazon SQS JSON API responses When you send a request to Amazon SQS, it returns a JSON response with the results. The response structure depends on the API action you used. To understand the details of these responses, see: • The specific API action in the API actions in the Amazon Simple Queue Service API Reference • The Amazon SQS AWS JSON protocol FAQs Successful JSON response structure If the request is successful, the main response element is x-amzn-RequestId, which contains the Universal Unique Identifier (UUID) of the request, as well as other appended response field(s). For example, the following CreateQueue response contains the QueueUrl field, which, in turn, contains the URL of the created queue. HTTP/1.1 200 OK x-amzn-RequestId: <requestId> Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "QueueUrl":"https://sqs.us-east-1.amazonaws.com/111122223333/MyQueue" } Interpreting Amazon SQS JSON API responses 144 Amazon Simple Queue Service Developer Guide JSON error response structure If a request is unsuccessful, Amazon SQS returns the main response, including the HTTP header and the body. In the HTTP header, x-amzn-RequestId contains the UUID of the request. x-amzn-query- error contains two pieces of information: the type of error, and whether the error was a producer or consumer error. In the response body, "__type" indicates other error details, and Message indicates the error condition in a readable format. The following is an example error response in JSON format: HTTP/1.1 400 Bad Request x-amzn-RequestId: 66916324-67ca-54bb-a410-3f567a7a0571 x-amzn-query-error: AWS.SimpleQueueService.NonExistentQueue;Sender Content-Length: <PayloadSizeBytes> Date: <Date> Content-Type: application/x-amz-json-1.0 { "__type": "com.amazonaws.sqs#QueueDoesNotExist", "message": "The specified queue does not exist." } Amazon SQS AWS JSON protocol FAQs This topic covers frequently asked questions about using AWS JSON protocol with Amazon SQS. What is AWS JSON protocol, and how does it differ from existing Amazon SQS API requests and responses? JSON is one of the most widely used and accepted wiring methods for communication between heterogeneous systems. Amazon SQS uses JSON as a medium to communicate between an AWS SDK client (for example, Java, Python, Golang, JavaScript) and Amazon SQS server. An HTTP request of an Amazon SQS API operation accepts input in the form of JSON. The Amazon SQS operation is executed and the response of execution is shared back to the SDK client in the form of JSON. Compared to AWS query, JSON is more efficient at transporting data between client and server. Amazon SQS AWS JSON protocol FAQs 145 Amazon Simple Queue Service Developer Guide • Amazon SQS AWS JSON protocol acts as a mediator between Amazon SQS client and server. • The server doesn’t understand the programming language in which the Amazon SQS operation is created, but it understands the AWS JSON protocol. • The Amazon SQS AWS JSON protocol uses the serialization (convert object to JSON format) and deserialization (convert JSON format to object) between the Amazon SQS client and server. How do I get started with AWS JSON protocols for Amazon SQS? To get started with the latest AWS SDK version to achieve faster messaging for Amazon SQS, upgrade your AWS SDK to the specified version or any subsequent version. To learn more about SDK clients, see the Guide column in the table below. The following is a list of SDK versions across language variants for AWS JSON protocol for use with Amazon SQS APIs: Language SDK client repository Required SDK client version Guide C++ aws/aws-sdk-cpp 1.11.98 AWS SDK for C++ Golang 1.x aws/aws-sdk-go v1.47.7 AWS SDK for Go Golang 2.x aws/aws-sdk-go-v2 v1.28.0 AWS SDK for Go V2 Java 1.x aws/aws-sdk-java 1.12.585 AWS SDK for Java Java 2.x aws/aws-sdk-java-v2 2.21.19 AWS SDK for Java JavaScript v2.x aws/aws-sdk-js JavaScript on AWS JavaScript v3.x aws/aws-sdk-js-v3 v3.447.0 JavaScript on AWS .NET aws/aws-sdk-net 3.7.681.0
|
sqs-dg-053
|
sqs-dg.pdf
| 53 |
To learn more about SDK clients, see the Guide column in the table below. The following is a list of SDK versions across language variants for AWS JSON protocol for use with Amazon SQS APIs: Language SDK client repository Required SDK client version Guide C++ aws/aws-sdk-cpp 1.11.98 AWS SDK for C++ Golang 1.x aws/aws-sdk-go v1.47.7 AWS SDK for Go Golang 2.x aws/aws-sdk-go-v2 v1.28.0 AWS SDK for Go V2 Java 1.x aws/aws-sdk-java 1.12.585 AWS SDK for Java Java 2.x aws/aws-sdk-java-v2 2.21.19 AWS SDK for Java JavaScript v2.x aws/aws-sdk-js JavaScript on AWS JavaScript v3.x aws/aws-sdk-js-v3 v3.447.0 JavaScript on AWS .NET aws/aws-sdk-net 3.7.681.0 AWS SDK for .NET Amazon SQS AWS JSON protocol FAQs 146 Amazon Simple Queue Service Developer Guide Language SDK client repository Required SDK client version Guide PHP aws/aws-sdk-php 3.285.2 AWS SDK for PHP Python-boto3 boto/boto3 1.28.82 Python-botocore boto/botocore 1.31.82 awscli AWS CLI 1.29.82 AWS SDK for Python (Boto3) AWS SDK for Python (Boto3) AWSCommand Line Interface Ruby aws/aws-sdk-ruby 1.67.0 AWS SDK for Ruby What are the risks of enabling JSON protocol for my Amazon SQS workloads? If you are using a custom implementation of AWS SDK or a combination of custom clients and AWS SDK to interact with Amazon SQS that generates AWS Query based (aka XML-based) responses, it may be incompatible with AWS JSON protocol. If you encounter any issues, contact AWS Support. What if I am already on the latest AWS SDK version, but my open sourced solution does not support JSON? You must change your SDK version to the version previous to what you are using. See How do I get started with AWS JSON protocols for Amazon SQS? for more information. AWS SDK versions listed in How do I get started with AWS JSON protocols for Amazon SQS? uses JSON wire protocol for Amazon SQS APIs. If you change your AWS SDK to the previous version, your Amazon SQS APIs will use the AWS query. What languages are supported for AWS JSON protocol used in Amazon SQS APIs? Amazon SQS supports all language variants where AWS SDKs are generally available (GA). Currently, we don't support Kotlin, Rust, or Swift. To learn more about other language variants, see Tools to Build on AWS. Amazon SQS AWS JSON protocol FAQs 147 Amazon Simple Queue Service Developer Guide What regions are supported for AWS JSON protocol used in Amazon SQS APIs Amazon SQS supports AWS JSON protocol in all AWS regions where Amazon SQS is available. What latency improvements can I expect when upgrading to the specified AWS SDK versions for Amazon SQS using the AWS JSON protocol? AWS JSON protocol is more efficient at serialization and deserialization of requests and responses when compared to AWS query protocol. Based on AWS performance tests for a 5 KB message payload, JSON protocol for Amazon SQS reduces end-to-end message processing latency by up to 23%, and reduces application client side CPU and memory usage. Will AWS query protocol be deprecated? AWS query protocol will continue to be supported. You can continue using AWS query protocol as long as your AWS SDK version is set any previous version other that what is listed in How do I get started with AWS JSON protocols for Amazon SQS. Where can I find more information about AWS JSON protocol? You can find more information about JSON protocol at AWS JSON 1.0 protocol in the Smithy documentation. For more about Amazon SQS API requests using AWS JSON protocol, see Making query API requests using AWS JSON protocol in Amazon SQS. Making query API requests using AWS query protocol in Amazon SQS This topic explains how to construct an Amazon SQS endpoint, make GET and POST requests, and interpret responses. Constructing an endpoint In order to work with Amazon SQS queues, you must construct an endpoint. For information about Amazon SQS endpoints, see the following pages in the Amazon Web Services General Reference: • Regional endpoints • Amazon Simple Queue Service endpoints and quotas Making query API requests using AWS query protocol 148 Amazon Simple Queue Service Developer Guide Every Amazon SQS endpoint is independent. For example, if two queues are named MyQueue and one has the endpoint sqs.us-east-2.amazonaws.com while the other has the endpoint sqs.eu-west-2.amazonaws.com, the two queues don't share any data with each other. The following is an example of an endpoint which makes a request to create a queue. https://sqs.eu-west-2.amazonaws.com/ ?Action=CreateQueue &DefaultVisibilityTimeout=40 &QueueName=MyQueue &Version=2012-11-05 &AUTHPARAMS Note Queue names and queue URLs are case sensitive. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Signing AWS API Requests in the Amazon Web Services General Reference. Making a GET request An Amazon SQS GET request is structured as a URL which consists of the following: • Endpoint – The resource that the request is acting on (the queue name
|
sqs-dg-054
|
sqs-dg.pdf
| 54 |
two queues don't share any data with each other. The following is an example of an endpoint which makes a request to create a queue. https://sqs.eu-west-2.amazonaws.com/ ?Action=CreateQueue &DefaultVisibilityTimeout=40 &QueueName=MyQueue &Version=2012-11-05 &AUTHPARAMS Note Queue names and queue URLs are case sensitive. The structure of AUTHPARAMS depends on the signature of the API request. For more information, see Signing AWS API Requests in the Amazon Web Services General Reference. Making a GET request An Amazon SQS GET request is structured as a URL which consists of the following: • Endpoint – The resource that the request is acting on (the queue name and URL), for example: https://sqs.us-east-2.amazonaws.com/123456789012/MyQueue • Action – The action that you want to perform on the endpoint. A question mark (?) separates the endpoint from the action, for example: ?Action=SendMessage&MessageBody=Your %20Message%20Text • Parameters – Any request parameters. Each parameter is separated by an ampersand (&), for example: &Version=2012-11-05&AUTHPARAMS The following is an example of a GET request that sends a message to an Amazon SQS queue. https://sqs.us-east-2.amazonaws.com/123456789012/MyQueue ?Action=SendMessage&MessageBody=Your%20message%20text &Version=2012-11-05 &AUTHPARAMS Making a GET request 149 Amazon Simple Queue Service Developer Guide Note Queue names and queue URLs are case sensitive. Because GET requests are URLs, you must URL-encode all parameter values. Because spaces aren't allowed in URLs, each space is URL-encoded as %20. The rest of the example isn't URL-encoded to make it easier to read. Making a POST request An Amazon SQS POST request sends query parameters as a form in the body of an HTTP request. The following is an example of an HTTP header with Content-Type set to application/x- www-form-urlencoded. POST /123456789012/MyQueue HTTP/1.1 Host: sqs.us-east-2.amazonaws.com Content-Type: application/x-www-form-urlencoded The header is followed by a form-urlencoded GET request that sends a message to an Amazon SQS queue. Each parameter is separated by an ampersand (&). Action=SendMessage &MessageBody=Your+Message+Text &Expires=2020-10-15T12%3A00%3A00Z &Version=2012-11-05 &AUTHPARAMS Note Only the Content-Type HTTP header is required. The AUTHPARAMS is the same as for the GET request. Your HTTP client might add other items to the HTTP request, according to the client's HTTP version. Making a POST request 150 Amazon Simple Queue Service Developer Guide Interpreting Amazon SQS XML API responses When you send a request to Amazon SQS, it returns an XML response containing the results of the request. To understand the structure and details of these responses, refer to the specific API actions in the Amazon Simple Queue Service API Reference. Successful XML response structure If the request is successful, the main response element is named after the action, with Response appended (for example, ActionNameResponse). This element contains the following child elements: • ActionNameResult – Contains an action-specific element. For example, the CreateQueueResult element contains the QueueUrl element which, in turn, contains the URL of the created queue. • ResponseMetadata – Contains the RequestId which, in turn, contains the Universal Unique Identifier (UUID) of the request. The following is an example successful response in XML format: <CreateQueueResponse xmlns=https://sqs.us-east-2.amazonaws.com/doc/2012-11-05/ xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:type=CreateQueueResponse> <CreateQueueResult> <QueueUrl>https://sqs.us-east-2.amazonaws.com/770098461991/queue2</QueueUrl> </CreateQueueResult> <ResponseMetadata> <RequestId>cb919c0a-9bce-4afe-9b48-9bdf2412bb67</RequestId> </ResponseMetadata> </CreateQueueResponse> XML error response structure If a request is unsuccessful, Amazon SQS always returns the main response element ErrorResponse. This element contains an Error element and a RequestId element. The Error element contains the following child elements: Interpreting Amazon SQS XML API responses 151 Amazon Simple Queue Service Developer Guide • Type – Specifies whether the error was a producer or consumer error. • Code – Specifies the type of error. • Message – Specifies the error condition in a readable format. • Detail – (Optional) Specifies additional details about the error. The RequestId element contains the UUID of the request. The following is an example error response in XML format: <ErrorResponse> <Error> <Type>Sender</Type> <Code>InvalidParameterValue</Code> <Message> Value (quename_nonalpha) for parameter QueueName is invalid. Must be an alphanumeric String of 1 to 80 in length. </Message> </Error> <RequestId>42d59b56-7407-4c4a-be0f-4c88daeea257</RequestId> </ErrorResponse> Authenticating requests for Amazon SQS Authentication is the process of identifying and verifying the party that sends a request. During the first stage of authentication, AWS verifies the identity of the producer and whether the producer is registered to use AWS (for more information, see Step 1: Create an AWS account and IAM user). Next, AWS abides by the following procedure: 1. 2. 3. The producer (sender) obtains the necessary credential. The producer sends a request and the credential to the consumer (receiver). The consumer uses the credential to verify whether the producer sent the request. 4. One of the following happens: • If authentication succeeds, the consumer processes the request. • If authentication fails, the consumer rejects the request and returns an error. Authenticating requests 152 Amazon Simple Queue Service Developer Guide Basic authentication process with HMAC-SHA When you access Amazon SQS using the Query API, you must provide the following items to authenticate your request: • The AWS Access Key ID that identifies your AWS account, which AWS uses
|
sqs-dg-055
|
sqs-dg.pdf
| 55 |
The producer sends a request and the credential to the consumer (receiver). The consumer uses the credential to verify whether the producer sent the request. 4. One of the following happens: • If authentication succeeds, the consumer processes the request. • If authentication fails, the consumer rejects the request and returns an error. Authenticating requests 152 Amazon Simple Queue Service Developer Guide Basic authentication process with HMAC-SHA When you access Amazon SQS using the Query API, you must provide the following items to authenticate your request: • The AWS Access Key ID that identifies your AWS account, which AWS uses to look up your Secret Access Key. • The HMAC-SHA request signature, calculated using your Secret Access Key (a shared secret known only to you and AWS—for more information, see RFC2104). The AWS SDK handles the signing process; however, if you submit a query request over HTTP or HTTPS, you must include a signature in every query request. 1. Derive a Signature Version 4 Signing Key. For more information, see Deriving the Signing Key with Java. Note Amazon SQS supports Signature Version 4, which provides improved SHA256-based security and performance over previous versions. When you create new applications that use Amazon SQS, use Signature Version 4. 2. Base64-encode the request signature. The following sample Java code does this: package amazon.webservices.common; // Define common routines for encoding data in AWS requests. public class Encoding { /* Perform base64 encoding of input bytes. * rawData is the array of bytes to be encoded. * return is the base64-encoded string representation of rawData. */ public static String EncodeBase64(byte[] rawData) { return Base64.encodeBytes(rawData); } } • The timestamp (or expiration) of the request. The timestamp that you use in the request must be a dateTime object, with the complete date, including hours, minutes, and seconds. For Basic authentication process with HMAC-SHA 153 Amazon Simple Queue Service Developer Guide example: 2007-01-31T23:59:59Z Although this isn't required, we recommend providing the object using the Coordinated Universal Time (Greenwich Mean Time) time zone. Note Make sure that your server time is set correctly. If you specify a timestamp (rather than an expiration), the request automatically expires 15 minutes after the specified time (AWS doesn't process requests with timestamps more than 15 minutes earlier than the current time on AWS servers). If you use .NET, you must not send overly specific timestamps (because of different interpretations of how extra time precision should be dropped). In this case, you should manually construct dateTime objects with precision of no more than one millisecond. Part 1: The request from the user The following is the process you must follow to authenticate AWS requests using an HMAC-SHA request signature. Part 1: The request from the user 154 Amazon Simple Queue Service Developer Guide 1. Construct a request to AWS. 2. Calculate a keyed-hash message authentication code (HMAC-SHA) signature using your Secret Access Key. 3. Include the signature and your Access Key ID in the request, and then send the request to AWS. Part 2: The response from AWS AWS begins the following process in response. Part 2: The response from AWS 155 Amazon Simple Queue Service Developer Guide 1. AWS uses the Access Key ID to look up your Secret Access Key. 2. AWS generates a signature from the request data and the Secret Access Key, using the same algorithm that you used to calculate the signature you sent in the request. 3. One of the following happens: • If the signature that AWS generates matches the one you send in the request, AWS considers the request to be authentic. • If the comparison fails, the request is discarded, and AWS returns an error. Amazon SQS batch actions Amazon SQS provides batch actions to help you reduce costs and manipulate up to 10 messages with a single action. These batch actions include: • SendMessageBatch • DeleteMessageBatch Batch actions 156 Amazon Simple Queue Service Developer Guide • ChangeMessageVisibilityBatch Using batch actions, you can perform multiple operations in a single API call, which helps optimize performance and reduce costs. You can take advantage of batch functionality using the query API or any AWS SDK that supports Amazon SQS batch actions. Important Details • Message Size Limit: The total size of all messages sent in a single SendMessageBatch call cannot exceed 262,144 bytes (256 KiB). • Permissions: You cannot set permissions explicitly for SendMessageBatch, DeleteMessageBatch, or ChangeMessageVisibilityBatch. Instead, setting permissions for SendMessage, DeleteMessage, or ChangeMessageVisibility sets permissions for the corresponding batch versions of the actions. • Console Support: The Amazon SQS console does not support batch actions. You must use the query API or an AWS SDK to perform batch operations. Batching message actions To further optimize costs and efficiency, consider the following best practices for batching message actions: • Batch API Actions: Use the Amazon
|
sqs-dg-056
|
sqs-dg.pdf
| 56 |
Limit: The total size of all messages sent in a single SendMessageBatch call cannot exceed 262,144 bytes (256 KiB). • Permissions: You cannot set permissions explicitly for SendMessageBatch, DeleteMessageBatch, or ChangeMessageVisibilityBatch. Instead, setting permissions for SendMessage, DeleteMessage, or ChangeMessageVisibility sets permissions for the corresponding batch versions of the actions. • Console Support: The Amazon SQS console does not support batch actions. You must use the query API or an AWS SDK to perform batch operations. Batching message actions To further optimize costs and efficiency, consider the following best practices for batching message actions: • Batch API Actions: Use the Amazon SQS batch API actions actions to send, receive, and delete messages, and to change the message visibility timeout for multiple messages with a single action. This reduces the number of API calls and associated costs. • Client-Side Buffering and Long Polling: Combine client-side buffering with request batching by using long polling together with the buffered asynchronous client included with the AWS SDK for Java. This approach helps to minimize the number of requests and optimizes the handling of large volumes of messages. Note The Amazon SQS Buffered Asynchronous Client doesn't currently support FIFO queues. Batching message actions 157 Amazon Simple Queue Service Developer Guide Enabling client-side buffering and request batching with Amazon SQS The AWS SDK for Java includes AmazonSQSBufferedAsyncClient which accesses Amazon SQS. This client allows for simple request batching using client-side buffering. Calls made from the client are first buffered and then sent as a batch request to Amazon SQS. Client-side buffering allows up to 10 requests to be buffered and sent as a batch request, decreasing your cost of using Amazon SQS and reducing the number of sent requests. AmazonSQSBufferedAsyncClient buffers both synchronous and asynchronous calls. Batched requests and support for long polling can also help increase throughput. For more information, see Increasing throughput using horizontal scaling and action batching with Amazon SQS. Because AmazonSQSBufferedAsyncClient implements the same interface as AmazonSQSAsyncClient, migrating from AmazonSQSAsyncClient to AmazonSQSBufferedAsyncClient typically requires only minimal changes to your existing code. Note The Amazon SQS Buffered Asynchronous Client doesn't currently support FIFO queues. Using AmazonSQSBufferedAsyncClient Before you begin, complete the steps in Setting up Amazon SQS. AWS SDK for Java 1.x For AWS SDK for Java 1.x, you can create a new AmazonSQSBufferedAsyncClient based on the following example: // Create the basic Amazon SQS async client final AmazonSQSAsync sqsAsync = new AmazonSQSAsyncClient(); // Create the buffered client final AmazonSQSAsync bufferedSqs = new AmazonSQSBufferedAsyncClient(sqsAsync); After you create the new AmazonSQSBufferedAsyncClient, you can use it to send multiple requests to Amazon SQS (just as you can with AmazonSQSAsyncClient), for example: final CreateQueueRequest createRequest = new CreateQueueRequest().withQueueName("MyQueue"); Enabling client-side buffering and request batching with Amazon SQS 158 Amazon Simple Queue Service Developer Guide final CreateQueueResult res = bufferedSqs.createQueue(createRequest); final SendMessageRequest request = new SendMessageRequest(); final String body = "Your message text" + System.currentTimeMillis(); request.setMessageBody( body ); request.setQueueUrl(res.getQueueUrl()); final Future<SendMessageResult> sendResult = bufferedSqs.sendMessageAsync(request); final ReceiveMessageRequest receiveRq = new ReceiveMessageRequest() .withMaxNumberOfMessages(1) .withQueueUrl(queueUrl); final ReceiveMessageResult rx = bufferedSqs.receiveMessage(receiveRq); Configuring AmazonSQSBufferedAsyncClient AmazonSQSBufferedAsyncClient is preconfigured with settings that work for most use cases. You can further configure AmazonSQSBufferedAsyncClient, for example: 1. Create an instance of the QueueBufferConfig class with the required configuration parameters. 2. Provide the instance to the AmazonSQSBufferedAsyncClient constructor. // Create the basic Amazon SQS async client final AmazonSQSAsync sqsAsync = new AmazonSQSAsyncClient(); final QueueBufferConfig config = new QueueBufferConfig() .withMaxInflightReceiveBatches(5) .withMaxDoneReceiveBatches(15); // Create the buffered client final AmazonSQSAsync bufferedSqs = new AmazonSQSBufferedAsyncClient(sqsAsync, config); QueueBufferConfig configuration parameters Parameter longPoll Default value Description true When longPoll is set to true, AmazonSQS Enabling client-side buffering and request batching with Amazon SQS 159 Amazon Simple Queue Service Developer Guide Parameter Default value Description longPollWaitTimeou 20 s tSeconds BufferedAsyncClient attempts to use long polling when it consumes messages. The maximum amount of time (in seconds) which a ReceiveMessage call blocks off on the server, waiting for messages to appear in the queue before returning with an empty receive result. Note When long polling is disabled, this setting has no effect. Enabling client-side buffering and request batching with Amazon SQS 160 Amazon Simple Queue Service Developer Guide Parameter Default value Description maxBatchOpenMs 200 ms The maximum amount of time (in milliseconds) that an outgoing call waits for other calls with which it batches messages of the same type. The higher the setting, the fewer batches are required to perform the same amount of work (however, the first call in a batch has to spend a longer time waiting). When you set this parameter to 0, submitted request s don't wait for other requests, effectively disabling batching. Enabling client-side buffering and request batching with Amazon SQS 161 Amazon Simple Queue Service Developer Guide Parameter Default value Description maxBatchSize 10 requests per batch maxBatchSizeBytes 256 KiB The maximum number of messages that are batched together in a
|
sqs-dg-057
|
sqs-dg.pdf
| 57 |
waits for other calls with which it batches messages of the same type. The higher the setting, the fewer batches are required to perform the same amount of work (however, the first call in a batch has to spend a longer time waiting). When you set this parameter to 0, submitted request s don't wait for other requests, effectively disabling batching. Enabling client-side buffering and request batching with Amazon SQS 161 Amazon Simple Queue Service Developer Guide Parameter Default value Description maxBatchSize 10 requests per batch maxBatchSizeBytes 256 KiB The maximum number of messages that are batched together in a single request. The higher the setting, the fewer batches are required to carry out the same number of requests. Note 10 requests per batch is the maximum allowed value for Amazon SQS. The maximum size of a message batch, in bytes, that the client attempts to send to Amazon SQS. Note 256 KiB is the maximum allowed value for Amazon SQS. Enabling client-side buffering and request batching with Amazon SQS 162 Amazon Simple Queue Service Developer Guide Parameter Default value Description maxDoneReceiveBatc 10 batches hes The maximum number of receive batches that AmazonSQSBufferedA syncClient and stores client-side. prefetches The higher the setting, the more receive requests can be satisfied without having to make a call to Amazon SQS (however, the more messages are prefetched, the longer they remain in the buffer, causing their own visibility timeout to expire). Note 0 indicates that all message pre- fetching is disabled and messages are consumed only on demand. Enabling client-side buffering and request batching with Amazon SQS 163 Amazon Simple Queue Service Developer Guide Parameter Default value Description maxInflightOutboun 5 batches dBatches The maximum number of active outbound batches that can be processed at the same time. The higher the setting, the faster outbound batches can be sent (subject to quotas such as CPU or bandwidth ) and the more threads are consumed by AmazonSQS BufferedAsyncClient . Enabling client-side buffering and request batching with Amazon SQS 164 Amazon Simple Queue Service Developer Guide Parameter Default value Description maxInflightReceive 10 batches Batches The maximum number of active receive batches that can be processed at the same time. The higher the setting, the more messages can be received (subject to quotas such as CPU or bandwidth ), and the more threads are consumed by AmazonSQS BufferedAsyncClient . Note 0 indicates that all message pre- fetching is disabled and messages are consumed only on demand. Enabling client-side buffering and request batching with Amazon SQS 165 Amazon Simple Queue Service Developer Guide Parameter Default value Description visibilityTimeoutS -1 econds When this parameter is set to a positive, non-zero value, t he visibility timeout set here overrides the visibility timeou t set on the queue from which messages are consumed. Note -1 indicates that the default setting is sele cted for the queue. You can't set visibility timeout to 0. AWS SDK for Java 2.x For AWS SDK for Java 2.x, you can create a new SqsAsyncBatchManager based on the following example: // Create the basic Sqs Async Client SqsAsyncClient sqs = SqsAsyncClient.builder() .region(Region.US_EAST_1) .build(); // Create the batch manager SqsAsyncBatchManager sqsAsyncBatchManager = sqs.batchManager(); After you create the new SqsAsyncBatchManager, you can use it to send multiple requests to Amazon SQS (just as you can with SqsAsyncClient), for example: final String queueName = "MyAsyncBufferedQueue" + UUID.randomUUID(); final CreateQueueRequest request = CreateQueueRequest.builder().queueName(queueName).build(); Enabling client-side buffering and request batching with Amazon SQS 166 Amazon Simple Queue Service Developer Guide final String queueUrl = sqs.createQueue(request).join().queueUrl(); System.out.println("Queue created: " + queueUrl); // Send messages CompletableFuture<SendMessageResponse> sendMessageFuture; for (int i = 0; i < 10; i++) { final int index = i; sendMessageFuture = sqsAsyncBatchManager.sendMessage( r -> r.messageBody("Message " + index).queueUrl(queueUrl)); SendMessageResponse response= sendMessageFuture.join(); System.out.println("Message " + response.messageId() + " sent!"); } // Receive messages with customized configurations CompletableFuture<ReceiveMessageResponse> receiveResponseFuture = customizedBatchManager.receiveMessage( r -> r.queueUrl(queueUrl) .waitTimeSeconds(10) .visibilityTimeout(20) .maxNumberOfMessages(10) ); System.out.println("You have received " + receiveResponseFuture.join().messages().size() + " messages in total."); // Delete messages DeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder().queueUrl(queueUrl).build(); int code = sqs.deleteQueue(deleteQueueRequest).join().sdkHttpResponse().statusCode(); System.out.println("Queue is deleted, with statusCode " + code); Configuring SqsAsyncBatchManager SqsAsyncBatchManager is preconfigured with settings that work for most use cases. You can further configure SqsAsyncBatchManager, for example: Creating custom configuration via SqsAsyncBatchManager.Builder: SqsAsyncBatchManager customizedBatchManager = SqsAsyncBatchManager.builder() .client(sqs) .scheduledExecutor(Executors.newScheduledThreadPool(5)) .overrideConfiguration(b -> b .maxBatchSize(10) Enabling client-side buffering and request batching with Amazon SQS 167 Amazon Simple Queue Service Developer Guide .sendRequestFrequency(Duration.ofMillis(200)) .receiveMessageMinWaitDuration(Duration.ofSeconds(10)) .receiveMessageVisibilityTimeout(Duration.ofSeconds(20)) .receiveMessageAttributeNames(Collections.singletonList("*")) .receiveMessageSystemAttributeNames(Collections.singletonList(MessageSystemAttributeName.ALL))) .build(); BatchOverrideConfiguration parameters Parameter Default value Description maxBatchSize 10 requests per batch sendRequestFrequency 200 ms The maximum number of messages that are batched together in a single request. The higher the setting, the fewer batches are required to carry out the same number of requests. Note The maximum allowed value for Amazon SQS is 10 requests per batch. The maximum amount of time (in milliseconds) that an outgoing
|
sqs-dg-058
|
sqs-dg.pdf
| 58 |
SqsAsyncBatchManager.Builder: SqsAsyncBatchManager customizedBatchManager = SqsAsyncBatchManager.builder() .client(sqs) .scheduledExecutor(Executors.newScheduledThreadPool(5)) .overrideConfiguration(b -> b .maxBatchSize(10) Enabling client-side buffering and request batching with Amazon SQS 167 Amazon Simple Queue Service Developer Guide .sendRequestFrequency(Duration.ofMillis(200)) .receiveMessageMinWaitDuration(Duration.ofSeconds(10)) .receiveMessageVisibilityTimeout(Duration.ofSeconds(20)) .receiveMessageAttributeNames(Collections.singletonList("*")) .receiveMessageSystemAttributeNames(Collections.singletonList(MessageSystemAttributeName.ALL))) .build(); BatchOverrideConfiguration parameters Parameter Default value Description maxBatchSize 10 requests per batch sendRequestFrequency 200 ms The maximum number of messages that are batched together in a single request. The higher the setting, the fewer batches are required to carry out the same number of requests. Note The maximum allowed value for Amazon SQS is 10 requests per batch. The maximum amount of time (in milliseconds) that an outgoing call waits for other calls with which it batches messages of the same type. The higher the setting, the fewer batches are required to perform the same amount of work (however, the first call in a batch has to spend a longer time waiting). Enabling client-side buffering and request batching with Amazon SQS 168 Amazon Simple Queue Service Developer Guide Parameter Default value Description receiveMessageVisi bilityTimeout -1 receiveMessageMinW aitDuration 50 ms When you set this parameter to 0, submitted request s don't wait for other requests, effectively disabling batching. When this parameter is set to a positive, non-zero value, the visibility timeout set here overrides the visibility timeout set on the queue from which messages are consumed. Note 1 indicates that the default setting is sele cted for the queue. You can't set visibility timeout to 0. The minimal amount of time (in milliseconds) that a receiveMessage call waits for available messages to be fetched. The higher the setting, the fewer batches are required to carry out the same number of request. Enabling client-side buffering and request batching with Amazon SQS 169 Amazon Simple Queue Service Developer Guide Increasing throughput using horizontal scaling and action batching with Amazon SQS Amazon SQS supports high-throughput messaging. For details on throughput limits, refer to Amazon SQS message quotas. To maximize throughput: • Scale producers and consumers horizontally by adding more instances of each. • Use action batching to send or receive multiple messages in a single request, reducing API call overhead. Horizontal scaling Because you access Amazon SQS through an HTTP request-response protocol, the request latency (the interval between initiating a request and receiving a response) limits the throughput that you can achieve from a single thread using a single connection. For example, if the latency from an Amazon EC2-based client to Amazon SQS in the same region averages 20 ms, the maximum throughput from a single thread over a single connection averages 50 TPS. Horizontal scaling involves increasing the number of message producers (which make SendMessage requests) and consumers (which make ReceiveMessage and DeleteMessage requests) in order to increase your overall queue throughput. You can scale horizontally in three ways: • Increase the number of threads per client • Add more clients • Increase the number of threads per client and add more clients When you add more clients, you achieve essentially linear gains in queue throughput. For example, if you double the number of clients, you also double the throughput. Action batching Batching performs more work during each round trip to the service (for example, when you send multiple messages with a single SendMessageBatch request). The Amazon SQS batch actions are SendMessageBatch, DeleteMessageBatch, and ChangeMessageVisibilityBatch. To take Increasing throughput using horizontal scaling and action batching with Amazon SQS 170 Amazon Simple Queue Service Developer Guide advantage of batching without changing your producers or consumers, you can use the Amazon SQS Buffered Asynchronous Client. Note Because ReceiveMessage can process 10 messages at a time, there is no ReceiveMessageBatch action. Batching distributes the latency of the batch action over the multiple messages in a batch request, rather than accept the entire latency for a single message (for example, a SendMessage request). Because each round trip carries more work, batch requests make more efficient use of threads and connections, improving throughput. You can combine batching with horizontal scaling to provide throughput with fewer threads, connections, and requests than individual message requests. You can use batched Amazon SQS actions to send, receive, or delete up to 10 messages at a time. Because Amazon SQS charges by the request, batching can substantially reduce your costs. Batching can introduce some complexity for your application (for example, you application must accumulate messages before sending them, or it sometimes must wait longer for a response). However, batching can be still effective in the following cases: • Your application generates many messages in a short time, so the delay is never very long. • A message consumer fetches messages from a queue at its discretion, unlike typical message producers that need to send messages in response to events they don't control. Important A batch request might succeed even though individual messages in the batch failed. After a batch request, always
|
sqs-dg-059
|
sqs-dg.pdf
| 59 |
can introduce some complexity for your application (for example, you application must accumulate messages before sending them, or it sometimes must wait longer for a response). However, batching can be still effective in the following cases: • Your application generates many messages in a short time, so the delay is never very long. • A message consumer fetches messages from a queue at its discretion, unlike typical message producers that need to send messages in response to events they don't control. Important A batch request might succeed even though individual messages in the batch failed. After a batch request, always check for individual message failures and retry the action if necessary. Increasing throughput using horizontal scaling and action batching with Amazon SQS 171 Amazon Simple Queue Service Developer Guide Working Java example for single-operation and batch requests Prerequisites Add the aws-java-sdk-sqs.jar, aws-java-sdk-ec2.jar, and commons-logging.jar packages to your Java build class path. The following example shows these dependencies in a Maven project pom.xml file. <dependencies> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-sqs</artifactId> <version>LATEST</version> </dependency> <dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-ec2</artifactId> <version>LATEST</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>LATEST</version> </dependency> </dependencies> SimpleProducerConsumer.java The following Java code example implements a simple producer-consumer pattern. The main thread spawns a number of producer and consumer threads that process 1 KB messages for a specified time. This example includes producers and consumers that make single-operation requests and those that make batch requests. /* * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://aws.amazon.com/apache2.0 * Increasing throughput using horizontal scaling and action batching with Amazon SQS 172 Amazon Simple Queue Service Developer Guide * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ import com.amazonaws.AmazonClientException; import com.amazonaws.ClientConfiguration; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.AmazonSQSClientBuilder; import com.amazonaws.services.sqs.model.*; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; /** * Start a specified number of producer and consumer threads, and produce-consume * for the least of the specified duration and 1 hour. Some messages can be left * in the queue because producers and consumers might not be in exact balance. */ public class SimpleProducerConsumer { // The maximum runtime of the program. private final static int MAX_RUNTIME_MINUTES = 60; private final static Log log = LogFactory.getLog(SimpleProducerConsumer.class); public static void main(String[] args) throws InterruptedException { final Scanner input = new Scanner(System.in); System.out.print("Enter the queue name: "); final String queueName = input.nextLine(); System.out.print("Enter the number of producers: "); final int producerCount = input.nextInt(); Increasing throughput using horizontal scaling and action batching with Amazon SQS 173 Amazon Simple Queue Service Developer Guide System.out.print("Enter the number of consumers: "); final int consumerCount = input.nextInt(); System.out.print("Enter the number of messages per batch: "); final int batchSize = input.nextInt(); System.out.print("Enter the message size in bytes: "); final int messageSizeByte = input.nextInt(); System.out.print("Enter the run time in minutes: "); final int runTimeMinutes = input.nextInt(); /* * Create a new instance of the builder with all defaults (credentials * and region) set automatically. For more information, see Creating * Service Clients in the AWS SDK for Java Developer Guide. */ final ClientConfiguration clientConfiguration = new ClientConfiguration() .withMaxConnections(producerCount + consumerCount); final AmazonSQS sqsClient = AmazonSQSClientBuilder.standard() .withClientConfiguration(clientConfiguration) .build(); final String queueUrl = sqsClient .getQueueUrl(new GetQueueUrlRequest(queueName)).getQueueUrl(); // The flag used to stop producer, consumer, and monitor threads. final AtomicBoolean stop = new AtomicBoolean(false); // Start the producers. final AtomicInteger producedCount = new AtomicInteger(); final Thread[] producers = new Thread[producerCount]; for (int i = 0; i < producerCount; i++) { if (batchSize == 1) { producers[i] = new Producer(sqsClient, queueUrl, messageSizeByte, producedCount, stop); } else { producers[i] = new BatchProducer(sqsClient, queueUrl, batchSize, messageSizeByte, producedCount, stop); } producers[i].start(); Increasing throughput using horizontal scaling and action batching with Amazon SQS 174 Amazon Simple Queue Service } Developer Guide // Start the consumers. final AtomicInteger consumedCount = new AtomicInteger(); final Thread[] consumers = new Thread[consumerCount]; for (int i = 0; i < consumerCount; i++) { if (batchSize == 1) { consumers[i] = new Consumer(sqsClient, queueUrl, consumedCount, stop); } else { consumers[i] = new BatchConsumer(sqsClient, queueUrl, batchSize, consumedCount, stop); } consumers[i].start(); } // Start the monitor thread. final Thread monitor = new Monitor(producedCount, consumedCount, stop); monitor.start(); // Wait for the specified amount of time then stop. Thread.sleep(TimeUnit.MINUTES.toMillis(Math.min(runTimeMinutes, MAX_RUNTIME_MINUTES))); stop.set(true); // Join all threads. for (int i = 0; i < producerCount; i++) { producers[i].join(); } for (int i = 0; i < consumerCount; i++) { consumers[i].join(); } monitor.interrupt(); monitor.join(); } private
|
sqs-dg-060
|
sqs-dg.pdf
| 60 |
Thread[] consumers = new Thread[consumerCount]; for (int i = 0; i < consumerCount; i++) { if (batchSize == 1) { consumers[i] = new Consumer(sqsClient, queueUrl, consumedCount, stop); } else { consumers[i] = new BatchConsumer(sqsClient, queueUrl, batchSize, consumedCount, stop); } consumers[i].start(); } // Start the monitor thread. final Thread monitor = new Monitor(producedCount, consumedCount, stop); monitor.start(); // Wait for the specified amount of time then stop. Thread.sleep(TimeUnit.MINUTES.toMillis(Math.min(runTimeMinutes, MAX_RUNTIME_MINUTES))); stop.set(true); // Join all threads. for (int i = 0; i < producerCount; i++) { producers[i].join(); } for (int i = 0; i < consumerCount; i++) { consumers[i].join(); } monitor.interrupt(); monitor.join(); } private static String makeRandomString(int sizeByte) { final byte[] bs = new byte[(int) Math.ceil(sizeByte * 5 / 8)]; new Random().nextBytes(bs); bs[0] = (byte) ((bs[0] | 64) & 127); return new BigInteger(bs).toString(32); } Increasing throughput using horizontal scaling and action batching with Amazon SQS 175 Amazon Simple Queue Service Developer Guide /** * The producer thread uses {@code SendMessage} * to send messages until it is stopped. */ private static class Producer extends Thread { final AmazonSQS sqsClient; final String queueUrl; final AtomicInteger producedCount; final AtomicBoolean stop; final String theMessage; Producer(AmazonSQS sqsQueueBuffer, String queueUrl, int messageSizeByte, AtomicInteger producedCount, AtomicBoolean stop) { this.sqsClient = sqsQueueBuffer; this.queueUrl = queueUrl; this.producedCount = producedCount; this.stop = stop; this.theMessage = makeRandomString(messageSizeByte); } /* * The producedCount object tracks the number of messages produced by * all producer threads. If there is an error, the program exits the * run() method. */ public void run() { try { while (!stop.get()) { sqsClient.sendMessage(new SendMessageRequest(queueUrl, theMessage)); producedCount.incrementAndGet(); } } catch (AmazonClientException e) { /* * By default, AmazonSQSClient retries calls 3 times before * failing. If this unlikely condition occurs, stop. */ log.error("Producer: " + e.getMessage()); System.exit(1); } } } Increasing throughput using horizontal scaling and action batching with Amazon SQS 176 Developer Guide Amazon Simple Queue Service /** * The producer thread uses {@code SendMessageBatch} * to send messages until it is stopped. */ private static class BatchProducer extends Thread { final AmazonSQS sqsClient; final String queueUrl; final int batchSize; final AtomicInteger producedCount; final AtomicBoolean stop; final String theMessage; BatchProducer(AmazonSQS sqsQueueBuffer, String queueUrl, int batchSize, int messageSizeByte, AtomicInteger producedCount, AtomicBoolean stop) { this.sqsClient = sqsQueueBuffer; this.queueUrl = queueUrl; this.batchSize = batchSize; this.producedCount = producedCount; this.stop = stop; this.theMessage = makeRandomString(messageSizeByte); } public void run() { try { while (!stop.get()) { final SendMessageBatchRequest batchRequest = new SendMessageBatchRequest().withQueueUrl(queueUrl); final List<SendMessageBatchRequestEntry> entries = new ArrayList<SendMessageBatchRequestEntry>(); for (int i = 0; i < batchSize; i++) entries.add(new SendMessageBatchRequestEntry() .withId(Integer.toString(i)) .withMessageBody(theMessage)); batchRequest.setEntries(entries); final SendMessageBatchResult batchResult = sqsClient.sendMessageBatch(batchRequest); producedCount.addAndGet(batchResult.getSuccessful().size()); /* * Because SendMessageBatch can return successfully, but * individual batch items fail, retry the failed batch items. Increasing throughput using horizontal scaling and action batching with Amazon SQS 177 Amazon Simple Queue Service */ Developer Guide if (!batchResult.getFailed().isEmpty()) { log.warn("Producer: retrying sending " + batchResult.getFailed().size() + " messages"); for (int i = 0, n = batchResult.getFailed().size(); i < n; i++) { sqsClient.sendMessage(new SendMessageRequest(queueUrl, theMessage)); producedCount.incrementAndGet(); } } } } catch (AmazonClientException e) { /* * By default, AmazonSQSClient retries calls 3 times before * failing. If this unlikely condition occurs, stop. */ log.error("BatchProducer: " + e.getMessage()); System.exit(1); } } } /** * The consumer thread uses {@code ReceiveMessage} and {@code DeleteMessage} * to consume messages until it is stopped. */ private static class Consumer extends Thread { final AmazonSQS sqsClient; final String queueUrl; final AtomicInteger consumedCount; final AtomicBoolean stop; Consumer(AmazonSQS sqsClient, String queueUrl, AtomicInteger consumedCount, AtomicBoolean stop) { this.sqsClient = sqsClient; this.queueUrl = queueUrl; this.consumedCount = consumedCount; this.stop = stop; } /* * Each consumer thread receives and deletes messages until the main * thread stops the consumer thread. The consumedCount object tracks the Increasing throughput using horizontal scaling and action batching with Amazon SQS 178 Amazon Simple Queue Service Developer Guide * number of messages that are consumed by all consumer threads, and the * count is logged periodically. */ public void run() { try { while (!stop.get()) { try { final ReceiveMessageResult result = sqsClient .receiveMessage(new ReceiveMessageRequest(queueUrl)); if (!result.getMessages().isEmpty()) { final Message m = result.getMessages().get(0); sqsClient.deleteMessage(new DeleteMessageRequest(queueUrl, m.getReceiptHandle())); consumedCount.incrementAndGet(); } } catch (AmazonClientException e) { log.error(e.getMessage()); } } } catch (AmazonClientException e) { /* * By default, AmazonSQSClient retries calls 3 times before * failing. If this unlikely condition occurs, stop. */ log.error("Consumer: " + e.getMessage()); System.exit(1); } } } /** * The consumer thread uses {@code ReceiveMessage} and {@code * DeleteMessageBatch} to consume messages until it is stopped. */ private static class BatchConsumer extends Thread { final AmazonSQS sqsClient; final String queueUrl; final int batchSize; final AtomicInteger consumedCount; final AtomicBoolean stop; Increasing throughput using horizontal scaling and action batching with Amazon SQS 179 Amazon Simple Queue Service Developer Guide BatchConsumer(AmazonSQS sqsClient, String queueUrl, int batchSize, AtomicInteger consumedCount, AtomicBoolean stop) { this.sqsClient = sqsClient; this.queueUrl = queueUrl; this.batchSize = batchSize; this.consumedCount = consumedCount; this.stop =
|
sqs-dg-061
|
sqs-dg.pdf
| 61 |
If this unlikely condition occurs, stop. */ log.error("Consumer: " + e.getMessage()); System.exit(1); } } } /** * The consumer thread uses {@code ReceiveMessage} and {@code * DeleteMessageBatch} to consume messages until it is stopped. */ private static class BatchConsumer extends Thread { final AmazonSQS sqsClient; final String queueUrl; final int batchSize; final AtomicInteger consumedCount; final AtomicBoolean stop; Increasing throughput using horizontal scaling and action batching with Amazon SQS 179 Amazon Simple Queue Service Developer Guide BatchConsumer(AmazonSQS sqsClient, String queueUrl, int batchSize, AtomicInteger consumedCount, AtomicBoolean stop) { this.sqsClient = sqsClient; this.queueUrl = queueUrl; this.batchSize = batchSize; this.consumedCount = consumedCount; this.stop = stop; } public void run() { try { while (!stop.get()) { final ReceiveMessageResult result = sqsClient .receiveMessage(new ReceiveMessageRequest(queueUrl) .withMaxNumberOfMessages(batchSize)); if (!result.getMessages().isEmpty()) { final List<Message> messages = result.getMessages(); final DeleteMessageBatchRequest batchRequest = new DeleteMessageBatchRequest() .withQueueUrl(queueUrl); final List<DeleteMessageBatchRequestEntry> entries = new ArrayList<DeleteMessageBatchRequestEntry>(); for (int i = 0, n = messages.size(); i < n; i++) entries.add(new DeleteMessageBatchRequestEntry() .withId(Integer.toString(i)) .withReceiptHandle(messages.get(i) .getReceiptHandle())); batchRequest.setEntries(entries); final DeleteMessageBatchResult batchResult = sqsClient .deleteMessageBatch(batchRequest); consumedCount.addAndGet(batchResult.getSuccessful().size()); /* * Because DeleteMessageBatch can return successfully, * but individual batch items fail, retry the failed * batch items. */ if (!batchResult.getFailed().isEmpty()) { final int n = batchResult.getFailed().size(); log.warn("Producer: retrying deleting " + n + " messages"); Increasing throughput using horizontal scaling and action batching with Amazon SQS 180 Amazon Simple Queue Service Developer Guide for (BatchResultErrorEntry e : batchResult .getFailed()) { sqsClient.deleteMessage( new DeleteMessageRequest(queueUrl, messages.get(Integer .parseInt(e.getId())) .getReceiptHandle())); consumedCount.incrementAndGet(); } } } } } catch (AmazonClientException e) { /* * By default, AmazonSQSClient retries calls 3 times before * failing. If this unlikely condition occurs, stop. */ log.error("BatchConsumer: " + e.getMessage()); System.exit(1); } } } /** * This thread prints every second the number of messages produced and * consumed so far. */ private static class Monitor extends Thread { private final AtomicInteger producedCount; private final AtomicInteger consumedCount; private final AtomicBoolean stop; Monitor(AtomicInteger producedCount, AtomicInteger consumedCount, AtomicBoolean stop) { this.producedCount = producedCount; this.consumedCount = consumedCount; this.stop = stop; } public void run() { try { while (!stop.get()) { Increasing throughput using horizontal scaling and action batching with Amazon SQS 181 Amazon Simple Queue Service Developer Guide Thread.sleep(1000); log.info("produced messages = " + producedCount.get() + ", consumed messages = " + consumedCount.get()); } } catch (InterruptedException e) { // Allow the thread to exit. } } } } Monitoring volume metrics from the example run Amazon SQS automatically generates volume metrics for sent, received, and deleted messages. You can access those metrics and others through the Monitoring tab for your queue or on the CloudWatch console. Note The metrics can take up to 15 minutes after the queue starts to become available. Using Amazon SQS with an AWS SDK AWS software development kits (SDKs) are available for many popular programming languages. Each SDK provides an API, code examples, and documentation that make it easier for developers to build applications in their preferred language. SDK documentation Code examples AWS SDK for C++ AWS SDK for C++ code examples AWS CLI AWS SDK for Go AWS SDK for Java AWS CLI code examples AWS SDK for Go code examples AWS SDK for Java code examples AWS SDK for JavaScript AWS SDK for JavaScript code examples Working with AWS SDKs 182 Amazon Simple Queue Service Developer Guide SDK documentation Code examples AWS SDK for Kotlin AWS SDK for Kotlin code examples AWS SDK for .NET AWS SDK for PHP AWS SDK for .NET code examples AWS SDK for PHP code examples AWS Tools for PowerShell Tools for PowerShell code examples AWS SDK for Python (Boto3) AWS SDK for Python (Boto3) code examples AWS SDK for Ruby AWS SDK for Rust AWS SDK for Ruby code examples AWS SDK for Rust code examples AWS SDK for SAP ABAP AWS SDK for SAP ABAP code examples AWS SDK for Swift AWS SDK for Swift code examples Example availability Can't find what you need? Request a code example by using the Provide feedback link at the bottom of this page. Working with AWS SDKs 183 Amazon Simple Queue Service Developer Guide Using JMS with Amazon SQS The Amazon SQS Java Messaging Library is a Java Message Service (JMS) interface for Amazon SQS that lets you take advantage of Amazon SQS in applications that already use JMS. The interface lets you use Amazon SQS as the JMS provider with minimal code changes. Together with the AWS SDK for Java, the Amazon SQS Java Messaging Library lets you create JMS connections and sessions, as well as producers and consumers that send and receive messages to and from Amazon SQS queues. The library supports sending and receiving messages to a queue (the JMS point-to-point model) according to the JMS 1.1 specification. The library supports sending text, byte, or object messages synchronously to Amazon SQS queues. The library also supports receiving objects synchronously or asynchronously. For
|
sqs-dg-062
|
sqs-dg.pdf
| 62 |
that already use JMS. The interface lets you use Amazon SQS as the JMS provider with minimal code changes. Together with the AWS SDK for Java, the Amazon SQS Java Messaging Library lets you create JMS connections and sessions, as well as producers and consumers that send and receive messages to and from Amazon SQS queues. The library supports sending and receiving messages to a queue (the JMS point-to-point model) according to the JMS 1.1 specification. The library supports sending text, byte, or object messages synchronously to Amazon SQS queues. The library also supports receiving objects synchronously or asynchronously. For information about features of the Amazon SQS Java Messaging Library that support the JMS 1.1 specification, see Amazon SQS supported JMS 1.1 implementations and the Amazon SQS FAQs. Prerequisites for working with JMS and Amazon SQS Before you begin, you must have the following prerequisites: • SDK for Java There are two ways to include the SDK for Java in your project: • Download and install the SDK for Java. • Use Maven to get the Amazon SQS Java Messaging Library. Note The SDK for Java is included as a dependency. The SDK for Java and Amazon SQS Extended Client Library for Java require the J2SE Development Kit 8.0 or later. For information about downloading the SDK for Java, see SDK for Java. • Amazon SQS Java Messaging Library Prerequisites 184 Amazon Simple Queue Service Developer Guide If you don't use Maven, you must add the amazon-sqs-java-messaging-lib.jar package to the Java class path. For information about downloading the library, see Amazon SQS Java Messaging Library. Note The Amazon SQS Java Messaging Library includes support for Maven and the Spring Framework. For code samples that use Maven, the Spring Framework, and the Amazon SQS Java Messaging Library, see Working Java examples for using JMS with Amazon SQS standard queues. <dependency> <groupId>com.amazonaws</groupId> <artifactId>amazon-sqs-java-messaging-lib</artifactId> <version>1.0.4</version> <type>jar</type> </dependency> • Amazon SQS Queue Create a queue using the AWS Management Console for Amazon SQS, the CreateQueue API, or the wrapped Amazon SQS client included in the Amazon SQS Java Messaging Library. • For information about creating a queue with Amazon SQS using either the AWS Management Console or the CreateQueue API, see Creating a Queue. • For information about using the Amazon SQS Java Messaging Library, see Using the Amazon SQS Java Messaging Library. Using the Amazon SQS Java Messaging Library To get started using the Java Message Service (JMS) with Amazon SQS, use the code examples in this section. The following sections show how to create a JMS connection and a session, and how to send and receive a message. The wrapped Amazon SQS client object included in the Amazon SQS Java Messaging Library checks if an Amazon SQS queue exists. If the queue doesn't exist, the client creates it. Using the Java Messaging Library 185 Amazon Simple Queue Service Developer Guide Creating a JMS connection Before you begin, see the prerequisites in Prerequisites for working with JMS and Amazon SQS. 1. Create a connection factory and call the createConnection method against the factory. // Create a new connection factory with all defaults (credentials and region) set automatically SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), AmazonSQSClientBuilder.defaultClient() ); // Create the connection. SQSConnection connection = connectionFactory.createConnection(); The SQSConnection class extends javax.jms.Connection. Together with the JMS standard connection methods, SQSConnection offers additional methods, such as getAmazonSQSClient and getWrappedAmazonSQSClient. Both methods let you perform administrative operations not included in the JMS specification, such as creating new queues. However, the getWrappedAmazonSQSClient method also provides a wrapped version of the Amazon SQS client used by the current connection. The wrapper transforms every exception from the client into an JMSException, allowing it to be more easily used by existing code that expects JMSException occurrences. 2. You can use the client objects returned from getAmazonSQSClient and getWrappedAmazonSQSClient to perform administrative operations not included in the JMS specification (for example, you can create an Amazon SQS queue). If you have existing code that expects JMS exceptions, then you should use getWrappedAmazonSQSClient: • If you use getWrappedAmazonSQSClient, the returned client object transforms all exceptions into JMS exceptions. • If you use getAmazonSQSClient, the exceptions are all Amazon SQS exceptions. Creating an Amazon SQS queue The wrapped client object checks if an Amazon SQS queue exists. Creating a JMS connection 186 Amazon Simple Queue Service Developer Guide If a queue doesn't exist, the client creates it. If the queue does exist, the function doesn't return anything. For more information, see the "Create the queue if needed" section in the TextMessageSender.java example. To create a standard queue // Get the wrapped client AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient(); // Create an SQS queue named MyQueue, if it doesn't already exist if (!client.queueExists("MyQueue")) { client.createQueue("MyQueue"); } To create a FIFO queue // Get the wrapped client AmazonSQSMessagingClientWrapper client
|
sqs-dg-063
|
sqs-dg.pdf
| 63 |
queue The wrapped client object checks if an Amazon SQS queue exists. Creating a JMS connection 186 Amazon Simple Queue Service Developer Guide If a queue doesn't exist, the client creates it. If the queue does exist, the function doesn't return anything. For more information, see the "Create the queue if needed" section in the TextMessageSender.java example. To create a standard queue // Get the wrapped client AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient(); // Create an SQS queue named MyQueue, if it doesn't already exist if (!client.queueExists("MyQueue")) { client.createQueue("MyQueue"); } To create a FIFO queue // Get the wrapped client AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient(); // Create an Amazon SQS FIFO queue named MyQueue.fifo, if it doesn't already exist if (!client.queueExists("MyQueue.fifo")) { Map<String, String> attributes = new HashMap<String, String>(); attributes.put("FifoQueue", "true"); attributes.put("ContentBasedDeduplication", "true"); client.createQueue(new CreateQueueRequest().withQueueName("MyQueue.fifo").withAttributes(attributes)); } Note The name of a FIFO queue must end with the .fifo suffix. For more information about the ContentBasedDeduplication attribute, see Exactly- once processing in Amazon SQS. Sending messages synchronously 1. When the connection and the underlying Amazon SQS queue are ready, create a nontransacted JMS session with AUTO_ACKNOWLEDGE mode. Sending messages synchronously 187 Amazon Simple Queue Service Developer Guide // Create the nontransacted session with AUTO_ACKNOWLEDGE mode Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 2. To send a text message to the queue, create a JMS queue identity and a message producer. // Create a queue identity and specify the queue name to the session Queue queue = session.createQueue("MyQueue"); // Create a producer for the 'MyQueue' MessageProducer producer = session.createProducer(queue); 3. Create a text message and send it to the queue. • To send a message to a standard queue, you don't need to set any additional parameters. // Create the text message TextMessage message = session.createTextMessage("Hello World!"); // Send the message producer.send(message); System.out.println("JMS Message " + message.getJMSMessageID()); • To send a message to a FIFO queue, you must set the message group ID. You can also set a message deduplication ID. For more information, see Amazon SQS FIFO queue key terms. // Create the text message TextMessage message = session.createTextMessage("Hello World!"); // Set the message group ID message.setStringProperty("JMSXGroupID", "Default"); // You can also set a custom message deduplication ID // message.setStringProperty("JMS_SQS_DeduplicationId", "hello"); // Here, it's not needed because content-based deduplication is enabled for the queue // Send the message producer.send(message); System.out.println("JMS Message " + message.getJMSMessageID()); System.out.println("JMS Message Sequence Number " + message.getStringProperty("JMS_SQS_SequenceNumber")); Sending messages synchronously 188 Amazon Simple Queue Service Developer Guide Receiving messages synchronously 1. To receive messages, create a consumer for the same queue and invoke the start method. You can call the start method on the connection at any time. However, the consumer doesn't begin to receive messages until you call it. // Create a consumer for the 'MyQueue' MessageConsumer consumer = session.createConsumer(queue); // Start receiving incoming messages connection.start(); 2. Call the receive method on the consumer with a timeout set to 1 second, and then print the contents of the received message. • After receiving a message from a standard queue, you can access the contents of the message. // Receive a message from 'MyQueue' and wait up to 1 second Message receivedMessage = consumer.receive(1000); // Cast the received message as TextMessage and display the text if (receivedMessage != null) { System.out.println("Received: " + ((TextMessage) receivedMessage).getText()); } • After receiving a message from a FIFO queue, you can access the contents of the message and other, FIFO-specific message attributes, such as the message group ID, message deduplication ID, and sequence number. For more information, see Amazon SQS FIFO queue key terms. // Receive a message from 'MyQueue' and wait up to 1 second Message receivedMessage = consumer.receive(1000); // Cast the received message as TextMessage and display the text if (receivedMessage != null) { System.out.println("Received: " + ((TextMessage) receivedMessage).getText()); System.out.println("Group id: " + receivedMessage.getStringProperty("JMSXGroupID")); System.out.println("Message deduplication id: " + receivedMessage.getStringProperty("JMS_SQS_DeduplicationId")); Receiving messages synchronously 189 Amazon Simple Queue Service Developer Guide System.out.println("Message sequence number: " + receivedMessage.getStringProperty("JMS_SQS_SequenceNumber")); } 3. Close the connection and the session. // Close the connection (and the session). connection.close(); The output looks similar to the following: JMS Message ID:8example-588b-44e5-bbcf-d816example2 Received: Hello World! Note You can use the Spring Framework to initialize these objects. For additional information, see SpringExampleConfiguration.xml, SpringExample.java, and the other helper classes in ExampleConfiguration.java and ExampleCommon.java in the Working Java examples for using JMS with Amazon SQS standard queues section. For complete examples of sending and receiving objects, see TextMessageSender.java and SyncMessageReceiver.java. Receiving messages asynchronously In the example in Using the Amazon SQS Java Messaging Library, a message is sent to MyQueue and received synchronously. The following example shows how to receive the messages asynchronously through a listener. 1. Implement the MessageListener interface. class MyListener implements MessageListener { @Override public void onMessage(Message message) { Receiving messages asynchronously 190 Amazon Simple Queue Service try { Developer Guide // Cast the
|
sqs-dg-064
|
sqs-dg.pdf
| 64 |
other helper classes in ExampleConfiguration.java and ExampleCommon.java in the Working Java examples for using JMS with Amazon SQS standard queues section. For complete examples of sending and receiving objects, see TextMessageSender.java and SyncMessageReceiver.java. Receiving messages asynchronously In the example in Using the Amazon SQS Java Messaging Library, a message is sent to MyQueue and received synchronously. The following example shows how to receive the messages asynchronously through a listener. 1. Implement the MessageListener interface. class MyListener implements MessageListener { @Override public void onMessage(Message message) { Receiving messages asynchronously 190 Amazon Simple Queue Service try { Developer Guide // Cast the received message as TextMessage and print the text to screen. System.out.println("Received: " + ((TextMessage) message).getText()); } catch (JMSException e) { e.printStackTrace(); } } } The onMessage method of the MessageListener interface is called when you receive a message. In this listener implementation, the text stored in the message is printed. 2. Instead of explicitly calling the receive method on the consumer, set the message listener of the consumer to an instance of the MyListener implementation. The main thread waits for one second. // Create a consumer for the 'MyQueue'. 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 is invoked when a message is received. Thread.sleep(1000); The rest of the steps are identical to the ones in the Using the Amazon SQS Java Messaging Library example. For a complete example of an asynchronous consumer, see AsyncMessageReceiver.java in Working Java examples for using JMS with Amazon SQS standard queues. The output for this example looks similar to the following: JMS Message ID:8example-588b-44e5-bbcf-d816example2 Received: Hello World! Receiving messages asynchronously 191 Amazon Simple Queue Service Developer Guide Using client acknowledge mode The example in Using the Amazon SQS Java Messaging Library uses AUTO_ACKNOWLEDGE mode where every received message is acknowledged automatically (and therefore deleted from the underlying Amazon SQS queue). 1. To explicitly acknowledge the messages after they're processed, you must create the session with CLIENT_ACKNOWLEDGE mode. // Create the non-transacted session with CLIENT_ACKNOWLEDGE mode. Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); 2. When the message is received, display it and then explicitly acknowledge it. // Cast the received message as TextMessage and print the text to screen. Also acknowledge the message. if (receivedMessage != null) { System.out.println("Received: " + ((TextMessage) receivedMessage).getText()); receivedMessage.acknowledge(); System.out.println("Acknowledged: " + message.getJMSMessageID()); } Note In this mode, when a message is acknowledged, all messages received before this message are implicitly acknowledged as well. For example, if 10 messages are received, and only the 10th message is acknowledged (in the order the messages are received), then all of the previous nine messages are also acknowledged. The rest of the steps are identical to the ones in the Using the Amazon SQS Java Messaging Library example. For a complete example of a synchronous consumer with client acknowledge mode, see SyncMessageReceiverClientAcknowledge.java in Working Java examples for using JMS with Amazon SQS standard queues. The output for this example looks similar to the following: JMS Message ID:4example-aa0e-403f-b6df-5e02example5 Received: Hello World! Using client acknowledge mode 192 Amazon Simple Queue Service Developer Guide Acknowledged: ID:4example-aa0e-403f-b6df-5e02example5 Using unordered acknowledge mode When using CLIENT_ACKNOWLEDGE mode, all messages received before an explicitly- acknowledged message are acknowledged automatically. For more information, see Using client acknowledge mode. The Amazon SQS Java Messaging Library provides another acknowledgement mode. When using UNORDERED_ACKNOWLEDGE mode, all received messages must be individually and explicitly acknowledged by the client, regardless of their reception order. To do this, create a session with UNORDERED_ACKNOWLEDGE mode. // Create the non-transacted session with UNORDERED_ACKNOWLEDGE mode. Session session = connection.createSession(false, SQSSession.UNORDERED_ACKNOWLEDGE); The remaining steps are identical to the ones in the Using client acknowledge mode example. For a complete example of a synchronous consumer with UNORDERED_ACKNOWLEDGE mode, see SyncMessageReceiverUnorderedAcknowledge.java. In this example, the output looks similar to the following: JMS Message ID:dexample-73ad-4adb-bc6c-4357example7 Received: Hello World! Acknowledged: ID:dexample-73ad-4adb-bc6c-4357example7 Using the Java Message Service with other Amazon SQS clients Using the Amazon SQS Java Message Service (JMS) Client with the AWS SDK limits Amazon SQS message size to 256 KB. However, you can create a JMS provider using any Amazon SQS client. For example, you can use the JMS Client with the Amazon SQS Extended Client Library for Java to send an Amazon SQS message that contains a reference to a message payload (up to 2 GB) in Amazon S3. For more information, see Managing large Amazon SQS messages using Java and Amazon S3. The following Java code example creates the JMS provider for the Extended Client Library. See the prerequisites in Prerequisites for working with JMS and Amazon SQS before testing this example. Using unordered acknowledge mode 193 Amazon Simple Queue Service Developer Guide AmazonS3 s3 = new AmazonS3Client(credentials); Region s3Region
|
sqs-dg-065
|
sqs-dg.pdf
| 65 |
For example, you can use the JMS Client with the Amazon SQS Extended Client Library for Java to send an Amazon SQS message that contains a reference to a message payload (up to 2 GB) in Amazon S3. For more information, see Managing large Amazon SQS messages using Java and Amazon S3. The following Java code example creates the JMS provider for the Extended Client Library. See the prerequisites in Prerequisites for working with JMS and Amazon SQS before testing this example. Using unordered acknowledge mode 193 Amazon Simple Queue Service Developer Guide AmazonS3 s3 = new AmazonS3Client(credentials); Region s3Region = Region.getRegion(Regions.US_WEST_2); s3.setRegion(s3Region); // Set the Amazon S3 bucket name, and set a lifecycle rule on the bucket to // permanently delete objects a certain number of days after each object's creation date. // Next, create the bucket, and enable message objects to be stored in the bucket. BucketLifecycleConfiguration.Rule expirationRule = new BucketLifecycleConfiguration.Rule(); expirationRule.withExpirationInDays(14).withStatus("Enabled"); BucketLifecycleConfiguration lifecycleConfig = new BucketLifecycleConfiguration().withRules(expirationRule); s3.createBucket(s3BucketName); s3.setBucketLifecycleConfiguration(s3BucketName, lifecycleConfig); System.out.println("Bucket created and configured."); // Set the SQS extended client configuration with large payload support enabled. ExtendedClientConfiguration extendedClientConfig = new ExtendedClientConfiguration() .withLargePayloadSupportEnabled(s3, s3BucketName); AmazonSQS sqsExtended = new AmazonSQSExtendedClient(new AmazonSQSClient(credentials), extendedClientConfig); Region sqsRegion = Region.getRegion(Regions.US_WEST_2); sqsExtended.setRegion(sqsRegion); The following Java code example creates the connection factory: // Create the connection factory using the environment variable credential provider. // Pass the configured Amazon SQS Extended Client to the JMS connection factory. SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), sqsExtended ); // Create the connection. SQSConnection connection = connectionFactory.createConnection(); Using the JMS Client with other Amazon SQS clients 194 Amazon Simple Queue Service Developer Guide Working Java examples for using JMS with Amazon SQS standard queues The following code examples show how to use the Java Message Service (JMS) with Amazon SQS standard queues. For more information about working with FIFO queues, see To create a FIFO queue, Sending messages synchronously, and Receiving messages synchronously. (Receiving messages synchronously is the same for standard and FIFO queues. However, messages in FIFO queues contain more attributes.) See the prerequisites in Prerequisites for working with JMS and Amazon SQS before testing the following examples. ExampleConfiguration.java The following Java SDK v 1.x code example sets the default queue name, the region, and the credentials to be used with the other Java examples. /* * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ public class ExampleConfiguration { public static final String DEFAULT_QUEUE_NAME = "SQSJMSClientExampleQueue"; public static final Region DEFAULT_REGION = Region.getRegion(Regions.US_EAST_2); private static String getParameter( String args[], int i ) { if( i + 1 >= args.length ) { throw new IllegalArgumentException( "Missing parameter for " + args[i] ); Working Java examples for using JMS with standard queues 195 Amazon Simple Queue Service } return args[i+1]; } /** Developer Guide * Parse the command line and return the resulting config. If the config parsing fails * print the error and the usage message and then call System.exit * * @param app the app to use when printing the usage string * @param args the command line arguments * @return the parsed config */ public static ExampleConfiguration parseConfig(String app, String args[]) { try { return new ExampleConfiguration(args); } catch (IllegalArgumentException e) { System.err.println( "ERROR: " + e.getMessage() ); System.err.println(); System.err.println( "Usage: " + app + " [--queue <queue>] [--region <region>] [--credentials <credentials>] "); System.err.println( " or" ); System.err.println( " " + app + " <spring.xml>" ); System.exit(-1); return null; } } private ExampleConfiguration(String args[]) { for( int i = 0; i < args.length; ++i ) { String arg = args[i]; if( arg.equals( "--queue" ) ) { setQueueName(getParameter(args, i)); i++; } else if( arg.equals( "--region" ) ) { String regionName = getParameter(args, i); try { setRegion(Region.getRegion(Regions.fromName(regionName))); } catch( IllegalArgumentException e ) { throw new IllegalArgumentException( "Unrecognized region " + regionName ); } i++; } else if( arg.equals( "--credentials" ) ) { ExampleConfiguration.java 196 Amazon Simple Queue Service Developer Guide String credsFile = getParameter(args, i); try { setCredentialsProvider( new PropertiesFileCredentialsProvider(credsFile) ); } catch (AmazonClientException e) { throw new IllegalArgumentException("Error reading credentials from " + credsFile, e ); } i++; } else { throw new IllegalArgumentException("Unrecognized option " + arg); } } } private String queueName = DEFAULT_QUEUE_NAME; private Region region = DEFAULT_REGION; private AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain(); public String getQueueName() { return queueName; } public void setQueueName(String queueName) { this.queueName = queueName;
|
sqs-dg-066
|
sqs-dg.pdf
| 66 |
throw new IllegalArgumentException( "Unrecognized region " + regionName ); } i++; } else if( arg.equals( "--credentials" ) ) { ExampleConfiguration.java 196 Amazon Simple Queue Service Developer Guide String credsFile = getParameter(args, i); try { setCredentialsProvider( new PropertiesFileCredentialsProvider(credsFile) ); } catch (AmazonClientException e) { throw new IllegalArgumentException("Error reading credentials from " + credsFile, e ); } i++; } else { throw new IllegalArgumentException("Unrecognized option " + arg); } } } private String queueName = DEFAULT_QUEUE_NAME; private Region region = DEFAULT_REGION; private AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain(); public String getQueueName() { return queueName; } public void setQueueName(String queueName) { this.queueName = queueName; } public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } public AWSCredentialsProvider getCredentialsProvider() { return credentialsProvider; } public void setCredentialsProvider(AWSCredentialsProvider credentialsProvider) { // Make sure they're usable first credentialsProvider.getCredentials(); this.credentialsProvider = credentialsProvider; ExampleConfiguration.java 197 Amazon Simple Queue Service Developer Guide } } TextMessageSender.java The following Java code example creates a text message producer. /* * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ public class TextMessageSender { public static void main(String args[]) throws JMSException { ExampleConfiguration config = ExampleConfiguration.parseConfig("TextMessageSender", args); ExampleCommon.setupLogging(); // Create the connection factory based on the config SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), AmazonSQSClientBuilder.standard() .withRegion(config.getRegion().getName()) .withCredentials(config.getCredentialsProvider()) ); // Create the connection SQSConnection connection = connectionFactory.createConnection(); // Create the queue if needed ExampleCommon.ensureQueueExists(connection, config.getQueueName()); TextMessageSender.java 198 Amazon Simple Queue Service Developer Guide // Create the session Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer( session.createQueue( config.getQueueName() ) ); sendMessages(session, producer); // Close the connection. This closes the session automatically connection.close(); System.out.println( "Connection closed" ); } private static void sendMessages( Session session, MessageProducer producer ) { BufferedReader inputReader = new BufferedReader( new InputStreamReader( System.in, Charset.defaultCharset() ) ); try { String input; while( true ) { System.out.print( "Enter message to send (leave empty to exit): " ); input = inputReader.readLine(); if( input == null || input.equals("" ) ) break; TextMessage message = session.createTextMessage(input); producer.send(message); System.out.println( "Send message " + message.getJMSMessageID() ); } } catch (EOFException e) { // Just return on EOF } catch (IOException e) { System.err.println( "Failed reading input: " + e.getMessage() ); } catch (JMSException e) { System.err.println( "Failed sending message: " + e.getMessage() ); e.printStackTrace(); } } } SyncMessageReceiver.java The following Java code example creates a synchronous message consumer. SyncMessageReceiver.java 199 Amazon Simple Queue Service Developer Guide /* * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ public class SyncMessageReceiver { public static void main(String args[]) throws JMSException { ExampleConfiguration config = ExampleConfiguration.parseConfig("SyncMessageReceiver", args); ExampleCommon.setupLogging(); // Create the connection factory based on the config SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), AmazonSQSClientBuilder.standard() .withRegion(config.getRegion().getName()) .withCredentials(config.getCredentialsProvider()) ); // Create the connection SQSConnection connection = connectionFactory.createConnection(); // Create the queue if needed ExampleCommon.ensureQueueExists(connection, config.getQueueName()); // Create the session Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer( session.createQueue( config.getQueueName() ) ); connection.start(); SyncMessageReceiver.java 200 Amazon Simple Queue Service Developer Guide receiveMessages(session, consumer); // Close the connection. This closes the session automatically connection.close(); System.out.println( "Connection closed" ); } private static void receiveMessages( Session session, MessageConsumer consumer ) { try { while( true ) { System.out.println( "Waiting for messages"); // Wait 1 minute for a message Message message = consumer.receive(TimeUnit.MINUTES.toMillis(1)); if( message == null ) { System.out.println( "Shutting down after 1 minute of silence" ); break; } ExampleCommon.handleMessage(message); message.acknowledge(); System.out.println( "Acknowledged message " + message.getJMSMessageID() ); } } catch (JMSException e) { System.err.println( "Error receiving from SQS: " + e.getMessage() ); e.printStackTrace(); } } } AsyncMessageReceiver.java The following Java code example creates an asynchronous message consumer. /* * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License
|
sqs-dg-067
|
sqs-dg.pdf
| 67 |
= consumer.receive(TimeUnit.MINUTES.toMillis(1)); if( message == null ) { System.out.println( "Shutting down after 1 minute of silence" ); break; } ExampleCommon.handleMessage(message); message.acknowledge(); System.out.println( "Acknowledged message " + message.getJMSMessageID() ); } } catch (JMSException e) { System.err.println( "Error receiving from SQS: " + e.getMessage() ); e.printStackTrace(); } } } AsyncMessageReceiver.java The following Java code example creates an asynchronous message consumer. /* * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed AsyncMessageReceiver.java 201 Amazon Simple Queue Service Developer Guide * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ public class AsyncMessageReceiver { public static void main(String args[]) throws JMSException, InterruptedException { ExampleConfiguration config = ExampleConfiguration.parseConfig("AsyncMessageReceiver", args); ExampleCommon.setupLogging(); // Create the connection factory based on the config SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), AmazonSQSClientBuilder.standard() .withRegion(config.getRegion().getName()) .withCredentials(config.getCredentialsProvider()) ); // Create the connection SQSConnection connection = connectionFactory.createConnection(); // Create the queue if needed ExampleCommon.ensureQueueExists(connection, config.getQueueName()); // Create the session Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer( session.createQueue( config.getQueueName() ) ); // No messages are processed until this is called connection.start(); ReceiverCallback callback = new ReceiverCallback(); consumer.setMessageListener( callback ); callback.waitForOneMinuteOfSilence(); System.out.println( "Returning after one minute of silence" ); // Close the connection. This closes the session automatically connection.close(); System.out.println( "Connection closed" ); AsyncMessageReceiver.java 202 Amazon Simple Queue Service } Developer Guide private static class ReceiverCallback implements MessageListener { // Used to listen for message silence private volatile long timeOfLastMessage = System.nanoTime(); public void waitForOneMinuteOfSilence() throws InterruptedException { for(;;) { long timeSinceLastMessage = System.nanoTime() - timeOfLastMessage; long remainingTillOneMinuteOfSilence = TimeUnit.MINUTES.toNanos(1) - timeSinceLastMessage; if( remainingTillOneMinuteOfSilence < 0 ) { break; } TimeUnit.NANOSECONDS.sleep(remainingTillOneMinuteOfSilence); } } @Override public void onMessage(Message message) { try { ExampleCommon.handleMessage(message); message.acknowledge(); System.out.println( "Acknowledged message " + message.getJMSMessageID() ); timeOfLastMessage = System.nanoTime(); } catch (JMSException e) { System.err.println( "Error processing message: " + e.getMessage() ); e.printStackTrace(); } } } } SyncMessageReceiverClientAcknowledge.java The following Java code example creates a synchronous consumer with client acknowledge mode. /* * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * SyncMessageReceiverClientAcknowledge.java 203 Amazon Simple Queue Service Developer Guide * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * An example class to demonstrate the behavior of CLIENT_ACKNOWLEDGE mode for received messages. This example * complements the example given in {@link SyncMessageReceiverUnorderedAcknowledge} for UNORDERED_ACKNOWLEDGE mode. * * First, a session, a message producer, and a message consumer are created. Then, two messages are sent. Next, two messages * are received but only the second one is acknowledged. After waiting for the visibility time out period, an attempt to * receive another message is made. It's shown that no message is returned for this attempt since in CLIENT_ACKNOWLEDGE mode, * as expected, all the messages prior to the acknowledged messages are also acknowledged. * * This ISN'T the behavior for UNORDERED_ACKNOWLEDGE mode. Please see {@link SyncMessageReceiverUnorderedAcknowledge} * for an example. */ public class SyncMessageReceiverClientAcknowledge { // Visibility time-out for the queue. It must match to the one set for the queue for this example to work. private static final long TIME_OUT_SECONDS = 1; public static void main(String args[]) throws JMSException, InterruptedException { // Create the configuration for the example ExampleConfiguration config = ExampleConfiguration.parseConfig("SyncMessageReceiverClientAcknowledge", args); // Setup logging for the example SyncMessageReceiverClientAcknowledge.java 204 Amazon Simple Queue Service Developer Guide ExampleCommon.setupLogging(); // Create the connection factory based on the config SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), AmazonSQSClientBuilder.standard() .withRegion(config.getRegion().getName()) .withCredentials(config.getCredentialsProvider()) ); // Create the connection SQSConnection connection = connectionFactory.createConnection(); // Create the queue if needed ExampleCommon.ensureQueueExists(connection, config.getQueueName()); // Create the session with client acknowledge mode Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create the producer and consume MessageProducer producer = session.createProducer(session.createQueue(config.getQueueName())); MessageConsumer consumer = session.createConsumer(session.createQueue(config.getQueueName())); // Open the connection connection.start(); // Send two text messages sendMessage(producer, session, "Message 1"); sendMessage(producer, session, "Message 2"); // Receive a message and don't acknowledge it receiveMessage(consumer, false); // Receive another message and acknowledge it receiveMessage(consumer, true); // Wait for the visibility time out, so that unacknowledged messages reappear in the queue System.out.println("Waiting
|
sqs-dg-068
|
sqs-dg.pdf
| 68 |
AmazonSQSClientBuilder.standard() .withRegion(config.getRegion().getName()) .withCredentials(config.getCredentialsProvider()) ); // Create the connection SQSConnection connection = connectionFactory.createConnection(); // Create the queue if needed ExampleCommon.ensureQueueExists(connection, config.getQueueName()); // Create the session with client acknowledge mode Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); // Create the producer and consume MessageProducer producer = session.createProducer(session.createQueue(config.getQueueName())); MessageConsumer consumer = session.createConsumer(session.createQueue(config.getQueueName())); // Open the connection connection.start(); // Send two text messages sendMessage(producer, session, "Message 1"); sendMessage(producer, session, "Message 2"); // Receive a message and don't acknowledge it receiveMessage(consumer, false); // Receive another message and acknowledge it receiveMessage(consumer, true); // Wait for the visibility time out, so that unacknowledged messages reappear in the queue System.out.println("Waiting for visibility timeout..."); Thread.sleep(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS)); SyncMessageReceiverClientAcknowledge.java 205 Amazon Simple Queue Service Developer Guide // Attempt to receive another message and acknowledge it. This results in receiving no messages since // we have acknowledged the second message. Although we didn't explicitly acknowledge the first message, // in the CLIENT_ACKNOWLEDGE mode, all the messages received prior to the explicitly acknowledged message // are also acknowledged. Therefore, we have implicitly acknowledged the first message. receiveMessage(consumer, true); // Close the connection. This closes the session automatically connection.close(); System.out.println("Connection closed."); } /** * Sends a message through the producer. * * @param producer Message producer * @param session Session * @param messageText Text for the message to be sent * @throws JMSException */ private static void sendMessage(MessageProducer producer, Session session, String messageText) throws JMSException { // Create a text message and send it producer.send(session.createTextMessage(messageText)); } /** * Receives a message through the consumer synchronously with the default timeout (TIME_OUT_SECONDS). * If a message is received, the message is printed. If no message is received, "Queue is empty!" is * printed. * * @param consumer Message consumer * @param acknowledge If true and a message is received, the received message is acknowledged. * @throws JMSException */ private static void receiveMessage(MessageConsumer consumer, boolean acknowledge) throws JMSException { // Receive a message SyncMessageReceiverClientAcknowledge.java 206 Amazon Simple Queue Service Message message = consumer.receive(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS)); Developer Guide if (message == null) { System.out.println("Queue is empty!"); } else { // Since this queue has only text messages, cast the message object and print the text System.out.println("Received: " + ((TextMessage) message).getText()); // Acknowledge the message if asked if (acknowledge) message.acknowledge(); } } } SyncMessageReceiverUnorderedAcknowledge.java The following Java code example creates a synchronous consumer with unordered acknowledge mode. /* * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * An example class to demonstrate the behavior of UNORDERED_ACKNOWLEDGE mode for received messages. This example * complements the example given in {@link SyncMessageReceiverClientAcknowledge} for CLIENT_ACKNOWLEDGE mode. * SyncMessageReceiverUnorderedAcknowledge.java 207 Amazon Simple Queue Service Developer Guide * First, a session, a message producer, and a message consumer are created. Then, two messages are sent. Next, two messages * are received but only the second one is acknowledged. After waiting for the visibility time out period, an attempt to * receive another message is made. It's shown that the first message received in the prior attempt is returned again * for the second attempt. In UNORDERED_ACKNOWLEDGE mode, all the messages must be explicitly acknowledged no matter what * the order they're received. * * This ISN'T the behavior for CLIENT_ACKNOWLEDGE mode. Please see {@link SyncMessageReceiverClientAcknowledge} * for an example. */ public class SyncMessageReceiverUnorderedAcknowledge { // Visibility time-out for the queue. It must match to the one set for the queue for this example to work. private static final long TIME_OUT_SECONDS = 1; public static void main(String args[]) throws JMSException, InterruptedException { // Create the configuration for the example ExampleConfiguration config = ExampleConfiguration.parseConfig("SyncMessageReceiverUnorderedAcknowledge", args); // Setup logging for the example ExampleCommon.setupLogging(); // Create the connection factory based on the config SQSConnectionFactory connectionFactory = new SQSConnectionFactory( new ProviderConfiguration(), AmazonSQSClientBuilder.standard() .withRegion(config.getRegion().getName()) .withCredentials(config.getCredentialsProvider()) ); // Create the connection SQSConnection connection = connectionFactory.createConnection(); // Create the queue if needed ExampleCommon.ensureQueueExists(connection, config.getQueueName()); // Create the session with unordered acknowledge mode SyncMessageReceiverUnorderedAcknowledge.java 208 Amazon Simple Queue Service Developer Guide Session session = connection.createSession(false, SQSSession.UNORDERED_ACKNOWLEDGE); // Create the producer and consume MessageProducer producer = session.createProducer(session.createQueue(config.getQueueName())); MessageConsumer consumer = session.createConsumer(session.createQueue(config.getQueueName())); // Open the connection connection.start(); // Send two text messages sendMessage(producer, session, "Message 1"); sendMessage(producer, session, "Message 2"); // Receive a message and don't acknowledge it receiveMessage(consumer, false); // Receive another message and acknowledge it receiveMessage(consumer, true); // Wait for the visibility time out, so that unacknowledged messages reappear
|
sqs-dg-069
|
sqs-dg.pdf
| 69 |
// Create the connection SQSConnection connection = connectionFactory.createConnection(); // Create the queue if needed ExampleCommon.ensureQueueExists(connection, config.getQueueName()); // Create the session with unordered acknowledge mode SyncMessageReceiverUnorderedAcknowledge.java 208 Amazon Simple Queue Service Developer Guide Session session = connection.createSession(false, SQSSession.UNORDERED_ACKNOWLEDGE); // Create the producer and consume MessageProducer producer = session.createProducer(session.createQueue(config.getQueueName())); MessageConsumer consumer = session.createConsumer(session.createQueue(config.getQueueName())); // Open the connection connection.start(); // Send two text messages sendMessage(producer, session, "Message 1"); sendMessage(producer, session, "Message 2"); // Receive a message and don't acknowledge it receiveMessage(consumer, false); // Receive another message and acknowledge it receiveMessage(consumer, true); // Wait for the visibility time out, so that unacknowledged messages reappear in the queue System.out.println("Waiting for visibility timeout..."); Thread.sleep(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS)); // Attempt to receive another message and acknowledge it. This results in receiving the first message since // we have acknowledged only the second message. In the UNORDERED_ACKNOWLEDGE mode, all the messages must // be explicitly acknowledged. receiveMessage(consumer, true); // Close the connection. This closes the session automatically connection.close(); System.out.println("Connection closed."); } /** * Sends a message through the producer. * * @param producer Message producer * @param session Session SyncMessageReceiverUnorderedAcknowledge.java 209 Amazon Simple Queue Service Developer Guide * @param messageText Text for the message to be sent * @throws JMSException */ private static void sendMessage(MessageProducer producer, Session session, String messageText) throws JMSException { // Create a text message and send it producer.send(session.createTextMessage(messageText)); } /** * Receives a message through the consumer synchronously with the default timeout (TIME_OUT_SECONDS). * If a message is received, the message is printed. If no message is received, "Queue is empty!" is * printed. * * @param consumer Message consumer * @param acknowledge If true and a message is received, the received message is acknowledged. * @throws JMSException */ private static void receiveMessage(MessageConsumer consumer, boolean acknowledge) throws JMSException { // Receive a message Message message = consumer.receive(TimeUnit.SECONDS.toMillis(TIME_OUT_SECONDS)); if (message == null) { System.out.println("Queue is empty!"); } else { // Since this queue has only text messages, cast the message object and print the text System.out.println("Received: " + ((TextMessage) message).getText()); // Acknowledge the message if asked if (acknowledge) message.acknowledge(); } } } SpringExampleConfiguration.xml The following XML code example is a bean configuration file for SpringExample.java. SpringExampleConfiguration.xml 210 Amazon Simple Queue Service Developer Guide <!-- Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at https://aws.amazon.com/apache2.0 or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/ schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/ schema/util/spring-util-3.0.xsd "> <bean id="CredentialsProviderBean" class="com.amazonaws.auth.DefaultAWSCredentialsProviderChain"/> <bean id="ClientBuilder" class="com.amazonaws.services.sqs.AmazonSQSClientBuilder" factory-method="standard"> <property name="region" value="us-east-2"/> <property name="credentials" ref="CredentialsProviderBean"/> </bean> <bean id="ProviderConfiguration" class="com.amazon.sqs.javamessaging.ProviderConfiguration"> <property name="numberOfMessagesToPrefetch" value="5"/> </bean> SpringExampleConfiguration.xml 211 Amazon Simple Queue Service Developer Guide <bean id="ConnectionFactory" class="com.amazon.sqs.javamessaging.SQSConnectionFactory"> <constructor-arg ref="ProviderConfiguration" /> <constructor-arg ref="ClientBuilder" /> </bean> <bean id="Connection" class="javax.jms.Connection" factory-bean="ConnectionFactory" factory-method="createConnection" init-method="start" destroy-method="close" /> <bean id="QueueName" class="java.lang.String"> <constructor-arg value="SQSJMSClientExampleQueue"/> </bean> </beans> SpringExample.java The following Java code example uses the bean configuration file to initialize your objects. /* * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ public class SpringExample { public static void main(String args[]) throws JMSException { if( args.length != 1 || !args[0].endsWith(".xml")) { System.err.println( "Usage: " + SpringExample.class.getName() + " <spring config.xml>" ); System.exit(1); SpringExample.java 212 Amazon Simple Queue Service } Developer Guide File springFile = new File( args[0] ); if( !springFile.exists() || !springFile.canRead() ) { System.err.println( "File " + args[0] + " doesn't exist or isn't readable."); System.exit(2); } ExampleCommon.setupLogging(); FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext( "file://" + springFile.getAbsolutePath() ); Connection connection; try { connection = context.getBean(Connection.class); } catch( NoSuchBeanDefinitionException e ) { System.err.println( "Can't find the JMS connection to use: " + e.getMessage() ); System.exit(3); return; } String queueName; try { queueName = context.getBean("QueueName", String.class); } catch( NoSuchBeanDefinitionException e ) { System.err.println( "Can't find the name of the queue to use: " + e.getMessage() ); System.exit(3); return; } if( connection instanceof SQSConnection ) { ExampleCommon.ensureQueueExists( (SQSConnection) connection, queueName ); } // Create the session Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer( session.createQueue( queueName) ); SpringExample.java 213 Amazon Simple Queue Service
|
sqs-dg-070
|
sqs-dg.pdf
| 70 |
= new FileSystemXmlApplicationContext( "file://" + springFile.getAbsolutePath() ); Connection connection; try { connection = context.getBean(Connection.class); } catch( NoSuchBeanDefinitionException e ) { System.err.println( "Can't find the JMS connection to use: " + e.getMessage() ); System.exit(3); return; } String queueName; try { queueName = context.getBean("QueueName", String.class); } catch( NoSuchBeanDefinitionException e ) { System.err.println( "Can't find the name of the queue to use: " + e.getMessage() ); System.exit(3); return; } if( connection instanceof SQSConnection ) { ExampleCommon.ensureQueueExists( (SQSConnection) connection, queueName ); } // Create the session Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer( session.createQueue( queueName) ); SpringExample.java 213 Amazon Simple Queue Service Developer Guide receiveMessages(session, consumer); // The context can be setup to close the connection for us context.close(); System.out.println( "Context closed" ); } private static void receiveMessages( Session session, MessageConsumer consumer ) { try { while( true ) { System.out.println( "Waiting for messages"); // Wait 1 minute for a message Message message = consumer.receive(TimeUnit.MINUTES.toMillis(1)); if( message == null ) { System.out.println( "Shutting down after 1 minute of silence" ); break; } ExampleCommon.handleMessage(message); message.acknowledge(); System.out.println( "Acknowledged message" ); } } catch (JMSException e) { System.err.println( "Error receiving from SQS: " + e.getMessage() ); e.printStackTrace(); } } } ExampleCommon.java The following Java code example checks if an Amazon SQS queue exists and then creates one if it doesn't. It also includes example logging code. /* * Copyright 2010-2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * https://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed ExampleCommon.java 214 Amazon Simple Queue Service Developer Guide * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. * */ public class ExampleCommon { /** * A utility function to check the queue exists and create it if needed. For most * use cases this is usually done by an administrator before the application is run. */ public static void ensureQueueExists(SQSConnection connection, String queueName) throws JMSException { AmazonSQSMessagingClientWrapper client = connection.getWrappedAmazonSQSClient(); /** * In most cases, you can do this with just a createQueue call, but GetQueueUrl * (called by queueExists) is a faster operation for the common case where the queue * already exists. Also many users and roles have permission to call GetQueueUrl * but don't have permission to call CreateQueue. */ if( !client.queueExists(queueName) ) { client.createQueue( queueName ); } } public static void setupLogging() { // Setup logging BasicConfigurator.configure(); Logger.getRootLogger().setLevel(Level.WARN); } public static void handleMessage(Message message) throws JMSException { System.out.println( "Got message " + message.getJMSMessageID() ); System.out.println( "Content: "); if( message instanceof TextMessage ) { TextMessage txtMessage = ( TextMessage ) message; System.out.println( "\t" + txtMessage.getText() ); } else if( message instanceof BytesMessage ){ ExampleCommon.java 215 Amazon Simple Queue Service Developer Guide BytesMessage byteMessage = ( BytesMessage ) message; // Assume the length fits in an int - SQS only supports sizes up to 256k so that // should be true byte[] bytes = new byte[(int)byteMessage.getBodyLength()]; byteMessage.readBytes(bytes); System.out.println( "\t" + Base64.encodeAsString( bytes ) ); } else if( message instanceof ObjectMessage ) { ObjectMessage objMessage = (ObjectMessage) message; System.out.println( "\t" + objMessage.getObject() ); } } } Amazon SQS supported JMS 1.1 implementations The Amazon SQS Java Messaging Library supports the following JMS 1.1 implementations. For more information about the supported features and capabilities of the Amazon SQS Java Messaging Library, see the Amazon SQS FAQ. Supported common interfaces • Connection • ConnectionFactory • Destination • Session • MessageConsumer • MessageProducer Supported message types • ByteMessage • ObjectMessage • TextMessage Supported JMS 1.1 implementations 216 Amazon Simple Queue Service Developer Guide Supported message acknowledgment modes • AUTO_ACKNOWLEDGE • CLIENT_ACKNOWLEDGE • DUPS_OK_ACKNOWLEDGE • UNORDERED_ACKNOWLEDGE Note The UNORDERED_ACKNOWLEDGE mode isn't part of the JMS 1.1 specification. This mode helps Amazon SQS allow a JMS client to explicitly acknowledge a message. JMS-defined headers and reserved properties For sending messages When you send messages, you can set the following headers and properties for each message: • JMSXGroupID (required for FIFO queues, not allowed for standard queues) • JMS_SQS_DeduplicationId (optional for FIFO queues, not allowed for standard queues) After you send messages, Amazon SQS sets the following headers and properties for each message: • JMSMessageID • JMS_SQS_SequenceNumber (only for FIFO queues) For receiving messages When you receive messages, Amazon SQS sets the following headers and properties for each message: • JMSDestination • JMSMessageID • JMSRedelivered Supported message acknowledgment modes 217 Amazon Simple Queue Service • JMSXDeliveryCount • JMSXGroupID (only for FIFO queues) • JMS_SQS_DeduplicationId (only for FIFO queues) • JMS_SQS_SequenceNumber (only for FIFO queues) Developer Guide JMS-defined headers
|
sqs-dg-071
|
sqs-dg.pdf
| 71 |
(required for FIFO queues, not allowed for standard queues) • JMS_SQS_DeduplicationId (optional for FIFO queues, not allowed for standard queues) After you send messages, Amazon SQS sets the following headers and properties for each message: • JMSMessageID • JMS_SQS_SequenceNumber (only for FIFO queues) For receiving messages When you receive messages, Amazon SQS sets the following headers and properties for each message: • JMSDestination • JMSMessageID • JMSRedelivered Supported message acknowledgment modes 217 Amazon Simple Queue Service • JMSXDeliveryCount • JMSXGroupID (only for FIFO queues) • JMS_SQS_DeduplicationId (only for FIFO queues) • JMS_SQS_SequenceNumber (only for FIFO queues) Developer Guide JMS-defined headers and reserved properties 218 Amazon Simple Queue Service Developer Guide Amazon SQS tutorials This topic provides tutorials to help you explore Amazon SQS features and functionality. Tutorials • Creating an Amazon SQS queue using AWS CloudFormation • Tutorial: Sending a message to an Amazon SQS queue from Amazon Virtual Private Cloud Creating an Amazon SQS queue using AWS CloudFormation Use the AWS CloudFormation console along with a JSON or YAML template to create an Amazon SQS queue. For more details, see Working with AWS CloudFormation Templates and the AWS::SQS::Queue Resource in the AWS CloudFormation User Guide. To use AWS CloudFormation to create an Amazon SQS queue. 1. Copy the following JSON code to a file named MyQueue.json. To create a standard queue, omit the FifoQueue and ContentBasedDeduplication properties. For more information on content-based deduplication, see Exactly-once processing in Amazon SQS. Note The name of a FIFO queue must end with the .fifo suffix. { "AWSTemplateFormatVersion": "2010-09-09", "Resources": { "MyQueue": { "Properties": { "QueueName": "MyQueue.fifo", "FifoQueue": true, "ContentBasedDeduplication": true }, "Type": "AWS::SQS::Queue" } }, "Outputs": { Creating an Amazon SQS queue using AWS CloudFormation 219 Amazon Simple Queue Service "QueueName": { "Description": "The name of the queue", "Value": { Developer Guide "Fn::GetAtt": [ "MyQueue", "QueueName" ] } }, "QueueURL": { "Description": "The URL of the queue", "Value": { "Ref": "MyQueue" } }, "QueueARN": { "Description": "The ARN of the queue", "Value": { "Fn::GetAtt": [ "MyQueue", "Arn" ] } } } } 2. Sign in to the AWS CloudFormation console, and then choose Create Stack. 3. On the Specify Template panel, choose Upload a template file, choose your MyQueue.json file, and then choose Next. 4. On the Specify Details page, type MyQueue for Stack Name, and then choose Next. 5. On the Options page, choose Next. 6. On the Review page, choose Create. AWS CloudFormation begins to create the MyQueue stack and displays the CREATE_IN_PROGRESS status. When the process is complete, AWS CloudFormation displays the CREATE_COMPLETE status. Creating an Amazon SQS queue using AWS CloudFormation 220 Amazon Simple Queue Service Developer Guide 7. (Optional) To display the name, URL, and ARN of the queue, choose the name of the stack and then on the next page expand the Outputs section. Tutorial: Sending a message to an Amazon SQS queue from Amazon Virtual Private Cloud This tutorial shows you how to send messages to an Amazon SQS queue over a secure, private network. The network includes: • A VPC containing an Amazon EC2 instance. • An interface VPC endpoint, which allows the Amazon EC2 instance to connect to Amazon SQS without using the public internet. Even in a fully private network, you can connect to the Amazon EC2 instance and send messages to the Amazon SQS queue. For more information, see Amazon Virtual Private Cloud endpoints for Amazon SQS. Important • You can use Amazon Virtual Private Cloud only with HTTPS Amazon SQS endpoints. • When you configure Amazon SQS to send messages from Amazon VPC, you must enable private DNS and specify endpoints in the format sqs.us-east-2.amazonaws.com or sqs.us-east-2.api.aws for the dual-stack endpoint. • Amazon SQS also supports FIPS endpoints through PrivateLink using the com.amazonaws.region.sqs-fips endpoint service. You can connect to FIPS endpoints in the format sqs-fips.region.amazonaws.com. • When using the dual-stack endpoint in Amazon Virtual Private Cloud, requests will be sent using IPv4 and IPv6. • Private DNS doesn't support legacy endpoints such as queue.amazonaws.com or us- east-2.queue.amazonaws.com. Sending a message from a VPC 221 Amazon Simple Queue Service Developer Guide Step 1: Create an Amazon EC2 key pair A key pair lets you connect to an Amazon EC2 instance. It consists of a public key that encrypts your login information and a private key that decrypts it. 1. Sign in to the Amazon EC2 console. 2. On the navigation menu, under Network & Security, choose Key Pairs. 3. Choose Create Key Pair. 4. In the Create Key Pair dialog box, for Key pair name, enter SQS-VPCE-Tutorial-Key-Pair, and then choose Create. 5. Your browser downloads the private key file SQS-VPCE-Tutorial-Key-Pair.pem automatically. Important Save this file in a safe place. EC2 does not generate a .pem file for the same key pair a second time. 6. To allow an SSH client to
|
sqs-dg-072
|
sqs-dg.pdf
| 72 |
consists of a public key that encrypts your login information and a private key that decrypts it. 1. Sign in to the Amazon EC2 console. 2. On the navigation menu, under Network & Security, choose Key Pairs. 3. Choose Create Key Pair. 4. In the Create Key Pair dialog box, for Key pair name, enter SQS-VPCE-Tutorial-Key-Pair, and then choose Create. 5. Your browser downloads the private key file SQS-VPCE-Tutorial-Key-Pair.pem automatically. Important Save this file in a safe place. EC2 does not generate a .pem file for the same key pair a second time. 6. To allow an SSH client to connect to your EC2 instance, set the permissions for your private key file so that only your user can have read permissions for it, for example: chmod 400 SQS-VPCE-Tutorial-Key-Pair.pem Step 2: Create AWS resources To set up the necessary infrastructure, you must use an AWS CloudFormation template, which is a blueprint for creating a stack comprised of AWS resources, such as Amazon EC2 instances and Amazon SQS queues. The stack for this tutorial includes the following resources: • A VPC and the associated networking resources, including a subnet, a security group, an internet gateway, and a route table • An Amazon EC2 instance launched into the VPC subnet • An Amazon SQS queue Step 1: Create an Amazon EC2 key pair 222 Amazon Simple Queue Service Developer Guide 1. Download the AWS CloudFormation template named SQS-VPCE-Tutorial- CloudFormation.yaml from GitHub. 2. Sign in to the AWS CloudFormation console. 3. Choose Create Stack. 4. On the Select Template page, choose Upload a template to Amazon S3, select the SQS- VPCE-SQS-Tutorial-CloudFormation.yaml file, and then choose Next. 5. On the Specify Details page, do the following: a. b. c. For Stack name, enter SQS-VPCE-Tutorial-Stack. For KeyName, choose SQS-VPCE-Tutorial-Key-Pair. Choose Next. 6. On the Options page, choose Next. 7. On the Review page, in the Capabilities section, choose I acknowledge that AWS CloudFormation might create IAM resources with custom names., and then choose Create. AWS CloudFormation begins to create the stack and displays the CREATE_IN_PROGRESS status. When the process is complete, AWS CloudFormation displays the CREATE_COMPLETE status. Step 3: Confirm that your EC2 instance isn't publicly accessible Your AWS CloudFormation template launches an EC2 instance named SQS-VPCE-Tutorial-EC2- Instance into your VPC. This EC2 instance doesn't allow outbound traffic and isn't able to send messages to Amazon SQS. To verify this, you must connect to the instance, try to connect to a public endpoint, and then try to message Amazon SQS. 1. Sign in to the Amazon EC2 console. 2. On the navigation menu, under Instances, choose Instances. 3. Select SQS-VPCE-Tutorial-EC2Instance. 4. Copy the hostname under Public DNS, for example, ec2-203-0-113-0.us- west-2.compute.amazonaws.com. 5. From the directory that contains the key pair that you created earlier, connect to the instance using the following command, for example: ssh -i SQS-VPCE-Tutorial-Key-Pair.pem ec2-user@ec2-203-0-113-0.us- east-2.compute.amazonaws.com Step 3: Confirm that your EC2 instance isn't publicly accessible 223 Amazon Simple Queue Service Developer Guide 6. Try to connect to any public endpoint, for example: ping amazon.com The connection attempt fails, as expected. Sign in to the Amazon SQS console. From the list of queues, select the queue created by your AWS CloudFormation template, for example, VPCE-SQS-Tutorial-Stack-CFQueue-1ABCDEFGH2IJK. 7. 8. 9. On the Details table, copy the URL, for example, https://sqs.us- east-2.amazonaws.com/123456789012/. 10. From your EC2 instance, try to publish a message to the queue using the following command, for example: aws sqs send-message --region us-east-2 --endpoint-url https://sqs.us- east-2.amazonaws.com/ --queue-url https://sqs.us-east-2.amazonaws.com/123456789012/ --message-body "Hello from Amazon SQS." The sending attempt fails, as expected. Important Later, when you create a VPC endpoint for Amazon SQS, your sending attempt will succeed. Step 4: Create an Amazon VPC endpoint for Amazon SQS To connect your VPC to Amazon SQS, you must define an interface VPC endpoint. After you add the endpoint, you can use the Amazon SQS API from the EC2 instance in your VPC. This allows you to send messages to a queue within the AWS network without crossing the public internet. Note The EC2 instance still doesn't have access to other AWS services and endpoints on the internet. Step 4: Create an Amazon VPC endpoint for Amazon SQS 224 Amazon Simple Queue Service Developer Guide 1. Sign in to the Amazon VPC console. 2. On the navigation menu, choose Endpoints. 3. Choose Create Endpoint. 4. On the Create Endpoint page, for Service Name, choose the service name for Amazon SQS. Note The service names vary based on the current AWS Region. For example, if you are in US East (Ohio), the service name is com.amazonaws.us-east-2.sqs. 5. 6. 7. For VPC, choose SQS-VPCE-Tutorial-VPC. For Subnets, choose the subnet whose Subnet ID contains SQS-VPCE-Tutorial-Subnet. For Security group, choose Select security groups, and then choose the security group whose Group Name contains SQS VPCE Tutorial Security Group. 8. Choose Create
|
sqs-dg-073
|
sqs-dg.pdf
| 73 |
in to the Amazon VPC console. 2. On the navigation menu, choose Endpoints. 3. Choose Create Endpoint. 4. On the Create Endpoint page, for Service Name, choose the service name for Amazon SQS. Note The service names vary based on the current AWS Region. For example, if you are in US East (Ohio), the service name is com.amazonaws.us-east-2.sqs. 5. 6. 7. For VPC, choose SQS-VPCE-Tutorial-VPC. For Subnets, choose the subnet whose Subnet ID contains SQS-VPCE-Tutorial-Subnet. For Security group, choose Select security groups, and then choose the security group whose Group Name contains SQS VPCE Tutorial Security Group. 8. Choose Create endpoint. The interface VPC endpoint is created and its ID is displayed, for example, vpce-0ab1cdef2ghi3j456k. 9. Choose Close. The Amazon VPC console opens the Endpoints page. Amazon VPC begins to create the endpoint and displays the pending status. When the process is complete, Amazon VPC displays the available status. Step 5: Send a message to your Amazon SQS queue Now that your VPC includes an endpoint for Amazon SQS, you can connect to your EC2 instance and send messages to your queue. 1. Reconnect to your EC2 instance, for example: ssh -i SQS-VPCE-Tutorial-Key-Pair.pem ec2-user@ec2-203-0-113-0.us- east-2.compute.amazonaws.com 2. Try to publish a message to the queue again using the following command, for example: Step 5: Send a message to your Amazon SQS queue 225 Amazon Simple Queue Service Developer Guide aws sqs send-message --region us-east-2 --endpoint-url https://sqs.us- east-2.amazonaws.com/ --queue-url https://sqs.us-east-2.amazonaws.com/123456789012/ --message-body "Hello from Amazon SQS." The sending attempt succeeds and the MD5 digest of the message body and the message ID are displayed, for example: { "MD5OfMessageBody": "a1bcd2ef3g45hi678j90klmn12p34qr5", "MessageId": "12345a67-8901-2345-bc67-d890123e45fg" } For information about receiving and deleting the message from the queue created by your AWS CloudFormation template (for example, VPCE-SQS-Tutorial-Stack-CFQueue-1ABCDEFGH2IJK), see Receiving and deleting a message in Amazon SQS . For information about deleting your resources, see the following: • Deleting a VPC Endpoint in the Amazon VPC User Guide • Deleting an Amazon SQS queue • Terminate Your Instance in the Amazon EC2 User Guide • Deleting Your VPC in the Amazon VPC User Guide • Deleting a Stack on the AWS CloudFormation Console in the AWS CloudFormation User Guide • Deleting Your Key Pair in the Amazon EC2 User Guide Step 5: Send a message to your Amazon SQS queue 226 Amazon Simple Queue Service Developer Guide Code examples for Amazon SQS using AWS SDKs The following code examples show how to use Amazon SQS with an AWS software development kit (SDK). Actions are code excerpts from larger programs and must be run in context. While actions show you how to call individual service functions, you can see actions in context in their related scenarios. Scenarios are code examples that show you how to accomplish specific tasks by calling multiple functions within a service or combined with other AWS services. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Get started Hello Amazon SQS The following code examples show how to get started using Amazon SQS. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. using Amazon.SQS; using Amazon.SQS.Model; namespace SQSActions; public static class HelloSQS { static async Task Main(string[] args) { 227 Amazon Simple Queue Service Developer Guide var sqsClient = new AmazonSQSClient(); Console.WriteLine($"Hello Amazon SQS! Following are some of your queues:"); Console.WriteLine(); // You can use await and any of the async methods to get a response. // Let's get the first five queues. var response = await sqsClient.ListQueuesAsync( new ListQueuesRequest() { MaxResults = 5 }); foreach (var queue in response.QueueUrls) { Console.WriteLine($"\tQueue Url: {queue}"); Console.WriteLine(); } } } • For API details, see ListQueues in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Code for the CMakeLists.txt CMake file. # Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS sqs) 228 Amazon Simple Queue Service Developer Guide # Set this project's name. project("hello_sqs") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if(WINDOWS_BUILD
|
sqs-dg-074
|
sqs-dg.pdf
| 74 |
used by this project. set(SERVICE_COMPONENTS sqs) 228 Amazon Simple Queue Service Developer Guide # Set this project's name. project("hello_sqs") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if(WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif() add_executable(${PROJECT_NAME} hello_sqs.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES}) Code for the hello_sqs.cpp source file. #include <aws/core/Aws.h> 229 Amazon Simple Queue Service Developer Guide #include <aws/sqs/SQSClient.h> #include <aws/sqs/model/ListQueuesRequest.h> #include <iostream> /* * A "Hello SQS" starter application that initializes an Amazon Simple Queue Service * (Amazon SQS) client and lists the SQS queues in the current account. * * main function * * Usage: 'hello_sqs' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SQS::SQSClient sqsClient(clientConfig); Aws::Vector<Aws::String> allQueueUrls; Aws::String nextToken; // Next token is used to handle a paginated response. do { Aws::SQS::Model::ListQueuesRequest request; Aws::SQS::Model::ListQueuesOutcome outcome = sqsClient.ListQueues(request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::String> &pageOfQueueUrls = outcome.GetResult().GetQueueUrls(); if (!pageOfQueueUrls.empty()) { allQueueUrls.insert(allQueueUrls.cend(), pageOfQueueUrls.cbegin(), pageOfQueueUrls.cend()); } 230 Amazon Simple Queue Service } Developer Guide else { std::cerr << "Error with SQS::ListQueues. " << outcome.GetError().GetMessage() << std::endl; break; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); std::cout << "Hello Amazon SQS! You have " << allQueueUrls.size() << " queue" << (allQueueUrls.size() == 1 ? "" : "s") << " in your account." << std::endl; if (!allQueueUrls.empty()) { std::cout << "Here are your queue URLs." << std::endl; for (const Aws::String &queueUrl: allQueueUrls) { std::cout << " * " << queueUrl << std::endl; } } } Aws::ShutdownAPI(options); // Should only be called once. return 0; } • For API details, see ListQueues in AWS SDK for C++ API Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. 231 Amazon Simple Queue Service Developer Guide package main import ( "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sqs" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Queue Service // (Amazon SQS) client and list the queues in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { ctx := context.Background() sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } sqsClient := sqs.NewFromConfig(sdkConfig) fmt.Println("Let's list the queues for your account.") var queueUrls []string paginator := sqs.NewListQueuesPaginator(sqsClient, &sqs.ListQueuesInput{}) for paginator.HasMorePages() { output, err := paginator.NextPage(ctx) if err != nil { log.Printf("Couldn't get queues. Here's why: %v\n", err) break } else { queueUrls = append(queueUrls, output.QueueUrls...) } } if len(queueUrls) == 0 { fmt.Println("You don't have any queues!") } else { for _, queueUrl := range queueUrls { fmt.Printf("\t%v\n", queueUrl) } } 232 Amazon Simple Queue Service } Developer Guide • For API details, see ListQueues in AWS SDK for Go API Reference. 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. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.SqsException; import software.amazon.awssdk.services.sqs.paginators.ListQueuesIterable; /** * 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 */ public class HelloSQS { public static void main(String[] args) { SqsClient sqsClient = SqsClient.builder() .region(Region.US_WEST_2) .build(); listQueues(sqsClient); sqsClient.close(); } public static void listQueues(SqsClient sqsClient) { try { 233 Amazon Simple Queue Service Developer Guide ListQueuesIterable listQueues = sqsClient.listQueuesPaginator(); listQueues.stream() .flatMap(r -> r.queueUrls().stream()) .forEach(content -> System.out.println(" Queue URL: " + content.toLowerCase())); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see ListQueues in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Initialize an Amazon SQS client and list queues. import { SQSClient, paginateListQueues } from "@aws-sdk/client-sqs"; export
|
sqs-dg-075
|
sqs-dg.pdf
| 75 |
} public static void listQueues(SqsClient sqsClient) { try { 233 Amazon Simple Queue Service Developer Guide ListQueuesIterable listQueues = sqsClient.listQueuesPaginator(); listQueues.stream() .flatMap(r -> r.queueUrls().stream()) .forEach(content -> System.out.println(" Queue URL: " + content.toLowerCase())); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see ListQueues in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Initialize an Amazon SQS client and list queues. import { SQSClient, paginateListQueues } from "@aws-sdk/client-sqs"; export const helloSqs = async () => { // The configuration object (`{}`) is required. If the region and credentials // are omitted, the SDK uses your local configuration if it exists. const client = new SQSClient({}); // You can also use `ListQueuesCommand`, but to use that command you must // handle the pagination yourself. You can do that by sending the `ListQueuesCommand` // with the `NextToken` parameter from the previous request. const paginatedQueues = paginateListQueues({ client }, {}); const queues = []; 234 Amazon Simple Queue Service Developer Guide for await (const page of paginatedQueues) { if (page.QueueUrls?.length) { queues.push(...page.QueueUrls); } } const suffix = queues.length === 1 ? "" : "s"; console.log( `Hello, Amazon SQS! You have ${queues.length} queue${suffix} in your account.`, ); console.log(queues.map((t) => ` * ${t}`).join("\n")); }; • For API details, see ListQueues in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. package com.kotlin.sqs import aws.sdk.kotlin.services.sqs.SqsClient import aws.sdk.kotlin.services.sqs.paginators.listQueuesPaginated import kotlinx.coroutines.flow.transform suspend fun main() { listTopicsPag() } suspend fun listTopicsPag() { SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient .listQueuesPaginated { } 235 Amazon Simple Queue Service Developer Guide .transform { it.queueUrls?.forEach { queue -> emit(queue) } } .collect { queue -> println("The Queue URL is $queue") } } } • For API details, see ListQueues in AWS SDK for Kotlin API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. The Package.swift file. import PackageDescription let package = Package( name: "sqs-basics", // Let Xcode know the minimum Apple platforms supported. platforms: [ .macOS(.v13), .iOS(.v15) ], dependencies: [ // Dependencies declare other packages that this package depends on. .package( url: "https://github.com/awslabs/aws-sdk-swift", from: "1.0.0"), .package( url: "https://github.com/apple/swift-argument-parser.git", branch: "main" ) ], targets: [ 236 Amazon Simple Queue Service Developer Guide // Targets are the basic building blocks of a package, defining a module or a test suite. // Targets can depend on other targets in this package and products // from dependencies. .executableTarget( name: "sqs-basics", dependencies: [ .product(name: "AWSSQS", package: "aws-sdk-swift"), .product(name: "ArgumentParser", package: "swift-argument- parser") ], path: "Sources") ] ) The Swift source code, entry.swift. import ArgumentParser import AWSClientRuntime import AWSSQS import Foundation struct ExampleCommand: ParsableCommand { @Argument(help: "The URL of the Amazon SQS queue to delete") var queueUrl: String @Option(help: "Name of the Amazon Region to use (default: us-east-1)") var region = "us-east-1" static var configuration = CommandConfiguration( commandName: "deletequeue", abstract: """ This example shows how to delete an Amazon SQS queue. """, discussion: """ """ ) /// Called by ``main()`` to run the bulk of the example. func runAsync() async throws { let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) 237 Amazon Simple Queue Service Developer Guide do { _ = try await sqsClient.deleteQueue( input: DeleteQueueInput( queueUrl: queueUrl ) ) } catch _ as AWSSQS.QueueDoesNotExist { print("Error: The specified queue doesn't exist.") return } } } /// The program's asynchronous entry point. @main struct Main { static func main() async { let args = Array(CommandLine.arguments.dropFirst()) do { let command = try ExampleCommand.parse(args) try await command.runAsync() } catch { ExampleCommand.exit(withError: error) } } } • For API details, see ListQueues in AWS SDK for Swift API reference. Code examples • Basic examples for Amazon SQS using AWS SDKs • Hello Amazon SQS • Actions for Amazon SQS using AWS SDKs • Use AddPermission with a CLI • Use ChangeMessageVisibility with an AWS SDK or CLI • Use ChangeMessageVisibilityBatch with a CLI • Use CreateQueue with an AWS SDK or CLI 238 Amazon Simple Queue Service Developer Guide • Use DeleteMessage with an AWS SDK or CLI • Use DeleteMessageBatch with an AWS SDK or CLI • Use DeleteQueue with an AWS SDK or CLI • Use GetQueueAttributes with an AWS SDK or CLI • Use GetQueueUrl with an AWS SDK or CLI • Use ListDeadLetterSourceQueues with a CLI • Use ListQueues with an AWS SDK or CLI • Use PurgeQueue with a CLI • Use ReceiveMessage with an AWS SDK or CLI • Use RemovePermission with a
|
sqs-dg-076
|
sqs-dg.pdf
| 76 |
ChangeMessageVisibilityBatch with a CLI • Use CreateQueue with an AWS SDK or CLI 238 Amazon Simple Queue Service Developer Guide • Use DeleteMessage with an AWS SDK or CLI • Use DeleteMessageBatch with an AWS SDK or CLI • Use DeleteQueue with an AWS SDK or CLI • Use GetQueueAttributes with an AWS SDK or CLI • Use GetQueueUrl with an AWS SDK or CLI • Use ListDeadLetterSourceQueues with a CLI • Use ListQueues with an AWS SDK or CLI • Use PurgeQueue with a CLI • Use ReceiveMessage with an AWS SDK or CLI • Use RemovePermission with a CLI • Use SendMessage with an AWS SDK or CLI • Use SendMessageBatch with an AWS SDK or CLI • Use SetQueueAttributes with an AWS SDK or CLI • Scenarios for Amazon SQS using AWS SDKs • Create a web application that sends and retrieves messages by using Amazon SQS • Create a messenger application with Step Functions • Create an Amazon Textract explorer application • Create and publish to a FIFO Amazon SNS topic using an AWS SDK • Detect people and objects in a video with Amazon Rekognition using an AWS SDK • Receive and process Amazon S3 event notifications by using an AWS SDK • Publish Amazon SNS messages to Amazon SQS queues using an AWS SDK • Send and receive batches of messages with Amazon SQS using an AWS SDK • Use the AWS Message Processing Framework for .NET to publish and receive Amazon SQS messages • Use the Amazon SQS Java Messaging Library to work with the Java Message Service (JMS) interface for Amazon SQS • Work with queue tags and Amazon SQS using an AWS SDK • Serverless examples for Amazon SQS • Invoke a Lambda function from an Amazon SQS trigger • Reporting batch item failures for Lambda functions with an Amazon SQS trigger 239 Amazon Simple Queue Service Developer Guide Basic examples for Amazon SQS using AWS SDKs The following code examples show how to use the basics of Amazon Simple Queue Service with AWS SDKs. Examples • Hello Amazon SQS • Actions for Amazon SQS using AWS SDKs • Use AddPermission with a CLI • Use ChangeMessageVisibility with an AWS SDK or CLI • Use ChangeMessageVisibilityBatch with a CLI • Use CreateQueue with an AWS SDK or CLI • Use DeleteMessage with an AWS SDK or CLI • Use DeleteMessageBatch with an AWS SDK or CLI • Use DeleteQueue with an AWS SDK or CLI • Use GetQueueAttributes with an AWS SDK or CLI • Use GetQueueUrl with an AWS SDK or CLI • Use ListDeadLetterSourceQueues with a CLI • Use ListQueues with an AWS SDK or CLI • Use PurgeQueue with a CLI • Use ReceiveMessage with an AWS SDK or CLI • Use RemovePermission with a CLI • Use SendMessage with an AWS SDK or CLI • Use SendMessageBatch with an AWS SDK or CLI • Use SetQueueAttributes with an AWS SDK or CLI Hello Amazon SQS The following code examples show how to get started using Amazon SQS. Basics 240 Amazon Simple Queue Service .NET SDK for .NET Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. using Amazon.SQS; using Amazon.SQS.Model; namespace SQSActions; public static class HelloSQS { static async Task Main(string[] args) { var sqsClient = new AmazonSQSClient(); Console.WriteLine($"Hello Amazon SQS! Following are some of your queues:"); Console.WriteLine(); // You can use await and any of the async methods to get a response. // Let's get the first five queues. var response = await sqsClient.ListQueuesAsync( new ListQueuesRequest() { MaxResults = 5 }); foreach (var queue in response.QueueUrls) { Console.WriteLine($"\tQueue Url: {queue}"); Console.WriteLine(); } } } Hello Amazon SQS 241 Amazon Simple Queue Service Developer Guide • For API details, see ListQueues in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Code for the CMakeLists.txt CMake file. # Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS sqs) # Set this project's name. project("hello_sqs") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if(WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) Hello Amazon SQS 242 Amazon Simple
|
sqs-dg-077
|
sqs-dg.pdf
| 77 |
by this project. set(SERVICE_COMPONENTS sqs) # Set this project's name. project("hello_sqs") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if(WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) Hello Amazon SQS 242 Amazon Simple Queue Service Developer Guide # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif() add_executable(${PROJECT_NAME} hello_sqs.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES}) Code for the hello_sqs.cpp source file. #include <aws/core/Aws.h> #include <aws/sqs/SQSClient.h> #include <aws/sqs/model/ListQueuesRequest.h> #include <iostream> /* * A "Hello SQS" starter application that initializes an Amazon Simple Queue Service * (Amazon SQS) client and lists the SQS queues in the current account. * * main function * * Usage: 'hello_sqs' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optionally change the log level for debugging. // options.loggingOptions.logLevel = Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. { Aws::Client::ClientConfiguration clientConfig; Hello Amazon SQS 243 Amazon Simple Queue Service Developer Guide // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SQS::SQSClient sqsClient(clientConfig); Aws::Vector<Aws::String> allQueueUrls; Aws::String nextToken; // Next token is used to handle a paginated response. do { Aws::SQS::Model::ListQueuesRequest request; Aws::SQS::Model::ListQueuesOutcome outcome = sqsClient.ListQueues(request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::String> &pageOfQueueUrls = outcome.GetResult().GetQueueUrls(); if (!pageOfQueueUrls.empty()) { allQueueUrls.insert(allQueueUrls.cend(), pageOfQueueUrls.cbegin(), pageOfQueueUrls.cend()); } } else { std::cerr << "Error with SQS::ListQueues. " << outcome.GetError().GetMessage() << std::endl; break; } nextToken = outcome.GetResult().GetNextToken(); } while (!nextToken.empty()); std::cout << "Hello Amazon SQS! You have " << allQueueUrls.size() << " queue" << (allQueueUrls.size() == 1 ? "" : "s") << " in your account." << std::endl; if (!allQueueUrls.empty()) { std::cout << "Here are your queue URLs." << std::endl; for (const Aws::String &queueUrl: allQueueUrls) { std::cout << " * " << queueUrl << std::endl; } } Hello Amazon SQS 244 Amazon Simple Queue Service } Developer Guide Aws::ShutdownAPI(options); // Should only be called once. return 0; } • For API details, see ListQueues in AWS SDK for C++ API Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. package main import ( "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sqs" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Queue Service // (Amazon SQS) client and list the queues in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { ctx := context.Background() sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) Hello Amazon SQS 245 Amazon Simple Queue Service return Developer Guide } sqsClient := sqs.NewFromConfig(sdkConfig) fmt.Println("Let's list the queues for your account.") var queueUrls []string paginator := sqs.NewListQueuesPaginator(sqsClient, &sqs.ListQueuesInput{}) for paginator.HasMorePages() { output, err := paginator.NextPage(ctx) if err != nil { log.Printf("Couldn't get queues. Here's why: %v\n", err) break } else { queueUrls = append(queueUrls, output.QueueUrls...) } } if len(queueUrls) == 0 { fmt.Println("You don't have any queues!") } else { for _, queueUrl := range queueUrls { fmt.Printf("\t%v\n", queueUrl) } } } • For API details, see ListQueues in AWS SDK for Go API Reference. 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. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.SqsException; import software.amazon.awssdk.services.sqs.paginators.ListQueuesIterable; Hello Amazon SQS 246 Amazon Simple Queue Service Developer Guide /** * 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 */ public class HelloSQS { public static void main(String[] args) { SqsClient sqsClient = SqsClient.builder() .region(Region.US_WEST_2) .build(); listQueues(sqsClient); sqsClient.close(); } public static void listQueues(SqsClient sqsClient) { try { ListQueuesIterable listQueues = sqsClient.listQueuesPaginator(); listQueues.stream() .flatMap(r -> r.queueUrls().stream()) .forEach(content -> System.out.println(" Queue URL: " + content.toLowerCase())); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see ListQueues in AWS SDK for Java 2.x API Reference. Hello Amazon SQS 247 Amazon Simple Queue Service JavaScript SDK for JavaScript (v3) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples
|
sqs-dg-078
|
sqs-dg.pdf
| 78 |
public static void main(String[] args) { SqsClient sqsClient = SqsClient.builder() .region(Region.US_WEST_2) .build(); listQueues(sqsClient); sqsClient.close(); } public static void listQueues(SqsClient sqsClient) { try { ListQueuesIterable listQueues = sqsClient.listQueuesPaginator(); listQueues.stream() .flatMap(r -> r.queueUrls().stream()) .forEach(content -> System.out.println(" Queue URL: " + content.toLowerCase())); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see ListQueues in AWS SDK for Java 2.x API Reference. Hello Amazon SQS 247 Amazon Simple Queue Service JavaScript SDK for JavaScript (v3) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Initialize an Amazon SQS client and list queues. import { SQSClient, paginateListQueues } from "@aws-sdk/client-sqs"; export const helloSqs = async () => { // The configuration object (`{}`) is required. If the region and credentials // are omitted, the SDK uses your local configuration if it exists. const client = new SQSClient({}); // You can also use `ListQueuesCommand`, but to use that command you must // handle the pagination yourself. You can do that by sending the `ListQueuesCommand` // with the `NextToken` parameter from the previous request. const paginatedQueues = paginateListQueues({ client }, {}); const queues = []; for await (const page of paginatedQueues) { if (page.QueueUrls?.length) { queues.push(...page.QueueUrls); } } const suffix = queues.length === 1 ? "" : "s"; console.log( `Hello, Amazon SQS! You have ${queues.length} queue${suffix} in your account.`, ); console.log(queues.map((t) => ` * ${t}`).join("\n")); }; Hello Amazon SQS 248 Amazon Simple Queue Service Developer Guide • For API details, see ListQueues in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. package com.kotlin.sqs import aws.sdk.kotlin.services.sqs.SqsClient import aws.sdk.kotlin.services.sqs.paginators.listQueuesPaginated import kotlinx.coroutines.flow.transform suspend fun main() { listTopicsPag() } suspend fun listTopicsPag() { SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient .listQueuesPaginated { } .transform { it.queueUrls?.forEach { queue -> emit(queue) } } .collect { queue -> println("The Queue URL is $queue") } } } • For API details, see ListQueues in AWS SDK for Kotlin API reference. Hello Amazon SQS 249 Amazon Simple Queue Service Swift SDK for Swift Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. The Package.swift file. import PackageDescription let package = Package( name: "sqs-basics", // Let Xcode know the minimum Apple platforms supported. platforms: [ .macOS(.v13), .iOS(.v15) ], dependencies: [ // Dependencies declare other packages that this package depends on. .package( url: "https://github.com/awslabs/aws-sdk-swift", from: "1.0.0"), .package( url: "https://github.com/apple/swift-argument-parser.git", branch: "main" ) ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. // Targets can depend on other targets in this package and products // from dependencies. .executableTarget( name: "sqs-basics", dependencies: [ .product(name: "AWSSQS", package: "aws-sdk-swift"), .product(name: "ArgumentParser", package: "swift-argument- parser") ], Hello Amazon SQS 250 Amazon Simple Queue Service Developer Guide path: "Sources") ] ) The Swift source code, entry.swift. import ArgumentParser import AWSClientRuntime import AWSSQS import Foundation struct ExampleCommand: ParsableCommand { @Argument(help: "The URL of the Amazon SQS queue to delete") var queueUrl: String @Option(help: "Name of the Amazon Region to use (default: us-east-1)") var region = "us-east-1" static var configuration = CommandConfiguration( commandName: "deletequeue", abstract: """ This example shows how to delete an Amazon SQS queue. """, discussion: """ """ ) /// Called by ``main()`` to run the bulk of the example. func runAsync() async throws { let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) do { _ = try await sqsClient.deleteQueue( input: DeleteQueueInput( queueUrl: queueUrl ) ) } catch _ as AWSSQS.QueueDoesNotExist { print("Error: The specified queue doesn't exist.") return } Hello Amazon SQS 251 Amazon Simple Queue Service Developer Guide } } /// The program's asynchronous entry point. @main struct Main { static func main() async { let args = Array(CommandLine.arguments.dropFirst()) do { let command = try ExampleCommand.parse(args) try await command.runAsync() } catch { ExampleCommand.exit(withError: error) } } } • For API details, see ListQueues in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions for Amazon SQS using AWS SDKs The following code examples demonstrate how to perform individual Amazon SQS actions with AWS SDKs. Each example includes a link to GitHub, where you can find instructions for setting up and running the code. These excerpts call the Amazon SQS API and are code excerpts from larger programs that must be run in context. You can see actions in context in Scenarios for Amazon SQS using AWS SDKs . The
|
sqs-dg-079
|
sqs-dg.pdf
| 79 |
examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions for Amazon SQS using AWS SDKs The following code examples demonstrate how to perform individual Amazon SQS actions with AWS SDKs. Each example includes a link to GitHub, where you can find instructions for setting up and running the code. These excerpts call the Amazon SQS API and are code excerpts from larger programs that must be run in context. You can see actions in context in Scenarios for Amazon SQS using AWS SDKs . The following examples include only the most commonly used actions. For a complete list, see the Amazon Simple Queue Service API Reference. Examples • Use AddPermission with a CLI • Use ChangeMessageVisibility with an AWS SDK or CLI Actions 252 Amazon Simple Queue Service Developer Guide • Use ChangeMessageVisibilityBatch with a CLI • Use CreateQueue with an AWS SDK or CLI • Use DeleteMessage with an AWS SDK or CLI • Use DeleteMessageBatch with an AWS SDK or CLI • Use DeleteQueue with an AWS SDK or CLI • Use GetQueueAttributes with an AWS SDK or CLI • Use GetQueueUrl with an AWS SDK or CLI • Use ListDeadLetterSourceQueues with a CLI • Use ListQueues with an AWS SDK or CLI • Use PurgeQueue with a CLI • Use ReceiveMessage with an AWS SDK or CLI • Use RemovePermission with a CLI • Use SendMessage with an AWS SDK or CLI • Use SendMessageBatch with an AWS SDK or CLI • Use SetQueueAttributes with an AWS SDK or CLI Use AddPermission with a CLI The following code examples show how to use AddPermission. CLI AWS CLI To add a permission to a queue This example enables the specified AWS account to send messages to the specified queue. Command: aws sqs add-permission --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --label SendMessagesFromMyQueue --aws- account-ids 12345EXAMPLE --actions SendMessage Output: Actions 253 Amazon Simple Queue Service Developer Guide None. • For API details, see AddPermission in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example allows the specified AWS account to send messages from the specified queue. Add-SQSPermission -Action SendMessage -AWSAccountId 80398EXAMPLE -Label SendMessagesFromMyQueue -QueueUrl https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue • For API details, see AddPermission in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use ChangeMessageVisibility with an AWS SDK or CLI The following code examples show how to use ChangeMessageVisibility. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Actions 254 Amazon Simple Queue Service Developer Guide //! Changes the visibility timeout of a message in an Amazon Simple Queue Service //! (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. \param messageReceiptHandle: A message receipt handle. \param visibilityTimeoutSeconds: Visibility timeout in seconds. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::changeMessageVisibility( const Aws::String &queue_url, const Aws::String &messageReceiptHandle, int visibilityTimeoutSeconds, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::ChangeMessageVisibilityRequest request; request.SetQueueUrl(queue_url); request.SetReceiptHandle(messageReceiptHandle); request.SetVisibilityTimeout(visibilityTimeoutSeconds); auto outcome = sqsClient.ChangeMessageVisibility(request); if (outcome.IsSuccess()) { std::cout << "Successfully changed visibility of message " << messageReceiptHandle << " from queue " << queue_url << std::endl; } else { std::cout << "Error changing visibility of message from queue " << queue_url << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see ChangeMessageVisibility in AWS SDK for C++ API Reference. Actions 255 Amazon Simple Queue Service Developer Guide CLI AWS CLI To change a message's timeout visibility This example changes the specified message's timeout visibility to 10 hours (10 hours * 60 minutes * 60 seconds). Command: aws sqs change-message-visibility --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --receipt-handle AQEBTpyI...t6HyQg== -- visibility-timeout 36000 Output: None. • For API details, see ChangeMessageVisibility in AWS CLI Command Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Receive an Amazon SQS message and change its timeout visibility. import { ReceiveMessageCommand, ChangeMessageVisibilityCommand, SQSClient, } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; Actions 256 Amazon Simple Queue Service Developer Guide const receiveMessage = (queueUrl) => client.send( new ReceiveMessageCommand({ AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 1, MessageAttributeNames: ["All"], QueueUrl: queueUrl, WaitTimeSeconds: 1, }), ); export const main = async (queueUrl = SQS_QUEUE_URL) => { const { Messages } = await receiveMessage(queueUrl); const response = await client.send( new ChangeMessageVisibilityCommand({ QueueUrl: queueUrl, ReceiptHandle: Messages[0].ReceiptHandle, VisibilityTimeout: 20, }), ); console.log(response); return response; };
|
sqs-dg-080
|
sqs-dg.pdf
| 80 |
up and run in the AWS Code Examples Repository. Receive an Amazon SQS message and change its timeout visibility. import { ReceiveMessageCommand, ChangeMessageVisibilityCommand, SQSClient, } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; Actions 256 Amazon Simple Queue Service Developer Guide const receiveMessage = (queueUrl) => client.send( new ReceiveMessageCommand({ AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 1, MessageAttributeNames: ["All"], QueueUrl: queueUrl, WaitTimeSeconds: 1, }), ); export const main = async (queueUrl = SQS_QUEUE_URL) => { const { Messages } = await receiveMessage(queueUrl); const response = await client.send( new ChangeMessageVisibilityCommand({ QueueUrl: queueUrl, ReceiptHandle: Messages[0].ReceiptHandle, VisibilityTimeout: 20, }), ); console.log(response); return response; }; • For API details, see ChangeMessageVisibility in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Receive an Amazon SQS message and change its timeout visibility. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region to us-west-2 AWS.config.update({ region: "us-west-2" }); Actions 257 Amazon Simple Queue Service Developer Guide // Create the SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var queueURL = "https://sqs.REGION.amazonaws.com/ACCOUNT-ID/QUEUE-NAME"; var params = { AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 1, MessageAttributeNames: ["All"], QueueUrl: queueURL, }; sqs.receiveMessage(params, function (err, data) { if (err) { console.log("Receive Error", err); } else { // Make sure we have a message if (data.Messages != null) { var visibilityParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle, VisibilityTimeout: 20, // 20 second timeout }; sqs.changeMessageVisibility(visibilityParams, function (err, data) { if (err) { console.log("Delete Error", err); } else { console.log("Timeout Changed", data); } }); } else { console.log("No messages to change"); } } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see ChangeMessageVisibility in AWS SDK for JavaScript API Reference. Actions 258 Amazon Simple Queue Service PowerShell Tools for PowerShell Developer Guide Example 1: This example changes the visibility timeout for the message with the specified receipt handle in the specified queue to 10 hours (10 hours * 60 minutes * 60 seconds = 36000 seconds). Edit-SQSMessageVisibility -QueueUrl https://sqs.us- east-1.amazonaws.com/8039EXAMPLE/MyQueue -ReceiptHandle AQEBgGDh...J/Iqww== - VisibilityTimeout 36000 • For API details, see ChangeMessageVisibility in AWS Tools for PowerShell Cmdlet Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'aws-sdk-sqs' # v2: require 'aws-sdk' # Replace us-west-2 with the AWS Region you're using for Amazon SQS. sqs = Aws::SQS::Client.new(region: 'us-west-2') begin queue_name = 'my-queue' queue_url = sqs.get_queue_url(queue_name: queue_name).queue_url # Receive up to 10 messages receive_message_result_before = sqs.receive_message({ queue_url: queue_url, max_number_of_messages: 10 }) Actions 259 Amazon Simple Queue Service Developer Guide puts "Before attempting to change message visibility timeout: received #{receive_message_result_before.messages.count} message(s)." receive_message_result_before.messages.each do |message| sqs.change_message_visibility({ queue_url: queue_url, receipt_handle: message.receipt_handle, visibility_timeout: 30 # This message will not be visible for 30 seconds after first receipt. }) end # Try to retrieve the original messages after setting their visibility timeout. receive_message_result_after = sqs.receive_message({ queue_url: queue_url, max_number_of_messages: 10 }) puts "\nAfter attempting to change message visibility timeout: received #{receive_message_result_after.messages.count} message(s)." rescue Aws::SQS::Errors::NonExistentQueue puts "Cannot receive messages for a queue named '#{queue_name}', as it does not exist." end • For API details, see ChangeMessageVisibility in AWS SDK for Ruby API Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use ChangeMessageVisibilityBatch with a CLI The following code examples show how to use ChangeMessageVisibilityBatch. CLI AWS CLI To change multiple messages' timeout visibilities as a batch Actions 260 Amazon Simple Queue Service Developer Guide This example changes the 2 specified messages' timeout visibilities to 10 hours (10 hours * 60 minutes * 60 seconds). Command: aws sqs change-message-visibility-batch --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --entries file://change-message- visibility-batch.json Input file (change-message-visibility-batch.json): [ { "Id": "FirstMessage", "ReceiptHandle": "AQEBhz2q...Jf3kaw==", "VisibilityTimeout": 36000 }, { "Id": "SecondMessage", "ReceiptHandle": "AQEBkTUH...HifSnw==", "VisibilityTimeout": 36000 } ] Output: { "Successful": [ { "Id": "SecondMessage" }, { "Id": "FirstMessage" } ] } • For API details, see ChangeMessageVisibilityBatch in AWS CLI Command Reference. Actions 261 Amazon Simple Queue Service PowerShell Tools for PowerShell Developer Guide Example 1: This example changes the visibility timeout for 2 messages with the specified receipt handles in the specified queue. The first message's visibility timeout is changed to 10 hours (10 hours * 60 minutes * 60 seconds = 36000 seconds). The second message's visibility timeout is changed to 5 hours (5 hours * 60 minutes * 60 seconds = 18000 seconds). $changeVisibilityRequest1 = New-Object Amazon.SQS.Model.ChangeMessageVisibilityBatchRequestEntry $changeVisibilityRequest1.Id = "Request1" $changeVisibilityRequest1.ReceiptHandle = "AQEBd329...v6gl8Q==" $changeVisibilityRequest1.VisibilityTimeout = 36000 $changeVisibilityRequest2 = New-Object Amazon.SQS.Model.ChangeMessageVisibilityBatchRequestEntry $changeVisibilityRequest2.Id = "Request2" $changeVisibilityRequest2.ReceiptHandle = "AQEBgGDh...J/Iqww==" $changeVisibilityRequest2.VisibilityTimeout = 18000 Edit-SQSMessageVisibilityBatch -QueueUrl https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $changeVisibilityRequest1, $changeVisibilityRequest2 Output:
|
sqs-dg-081
|
sqs-dg.pdf
| 81 |
for PowerShell Developer Guide Example 1: This example changes the visibility timeout for 2 messages with the specified receipt handles in the specified queue. The first message's visibility timeout is changed to 10 hours (10 hours * 60 minutes * 60 seconds = 36000 seconds). The second message's visibility timeout is changed to 5 hours (5 hours * 60 minutes * 60 seconds = 18000 seconds). $changeVisibilityRequest1 = New-Object Amazon.SQS.Model.ChangeMessageVisibilityBatchRequestEntry $changeVisibilityRequest1.Id = "Request1" $changeVisibilityRequest1.ReceiptHandle = "AQEBd329...v6gl8Q==" $changeVisibilityRequest1.VisibilityTimeout = 36000 $changeVisibilityRequest2 = New-Object Amazon.SQS.Model.ChangeMessageVisibilityBatchRequestEntry $changeVisibilityRequest2.Id = "Request2" $changeVisibilityRequest2.ReceiptHandle = "AQEBgGDh...J/Iqww==" $changeVisibilityRequest2.VisibilityTimeout = 18000 Edit-SQSMessageVisibilityBatch -QueueUrl https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $changeVisibilityRequest1, $changeVisibilityRequest2 Output: Failed Successful ------ ---------- {} {Request2, Request1} • For API details, see ChangeMessageVisibilityBatch in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 262 Amazon Simple Queue Service Developer Guide Use CreateQueue with an AWS SDK or CLI The following code examples show how to use CreateQueue. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Publish messages to queues • Send and receive batches of messages • Use the Amazon SQS Java Messaging Library to work with the JMS interface .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create a queue with a specific name. /// <summary> /// Create a queue with a specific name. /// </summary> /// <param name="queueName">The name for the queue.</param> /// <param name="useFifoQueue">True to use a FIFO queue.</param> /// <returns>The url for the queue.</returns> public async Task<string> CreateQueueWithName(string queueName, bool useFifoQueue) { int maxMessage = 256 * 1024; var queueAttributes = new Dictionary<string, string> { { QueueAttributeName.MaximumMessageSize, maxMessage.ToString() } }; Actions 263 Amazon Simple Queue Service Developer Guide var createQueueRequest = new CreateQueueRequest() { QueueName = queueName, Attributes = queueAttributes }; if (useFifoQueue) { // Update the name if it is not correct for a FIFO queue. if (!queueName.EndsWith(".fifo")) { createQueueRequest.QueueName = queueName + ".fifo"; } // Add an attribute for a FIFO queue. createQueueRequest.Attributes.Add( QueueAttributeName.FifoQueue, "true"); } var createResponse = await _amazonSQSClient.CreateQueueAsync( new CreateQueueRequest() { QueueName = queueName }); return createResponse.QueueUrl; } Create an Amazon SQS queue and send a message to it. using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon; using Amazon.SQS; using Amazon.SQS.Model; public class CreateSendExample { // Specify your AWS Region (an example Region is shown). private static readonly string QueueName = "Example_Queue"; private static readonly RegionEndpoint ServiceRegion = RegionEndpoint.USWest2; Actions 264 Amazon Simple Queue Service Developer Guide private static IAmazonSQS client; public static async Task Main() { client = new AmazonSQSClient(ServiceRegion); var createQueueResponse = await CreateQueue(client, QueueName); string queueUrl = createQueueResponse.QueueUrl; Dictionary<string, MessageAttributeValue> messageAttributes = new Dictionary<string, MessageAttributeValue> { { "Title", new MessageAttributeValue { DataType = "String", StringValue = "The Whistler" } }, { "Author", new MessageAttributeValue { DataType = "String", StringValue = "John Grisham" } }, { "WeeksOn", new MessageAttributeValue { DataType = "Number", StringValue = "6" } }, }; string messageBody = "Information about current NY Times fiction bestseller for week of 12/11/2016."; var sendMsgResponse = await SendMessage(client, queueUrl, messageBody, messageAttributes); } /// <summary> /// Creates a new Amazon SQS queue using the queue name passed to it /// in queueName. /// </summary> /// <param name="client">An SQS client object used to send the message.</ param> /// <param name="queueName">A string representing the name of the queue /// to create.</param> /// <returns>A CreateQueueResponse that contains information about the /// newly created queue.</returns> public static async Task<CreateQueueResponse> CreateQueue(IAmazonSQS client, string queueName) { var request = new CreateQueueRequest { QueueName = queueName, Attributes = new Dictionary<string, string> Actions 265 Amazon Simple Queue Service { Developer Guide { "DelaySeconds", "60" }, { "MessageRetentionPeriod", "86400" }, }, }; var response = await client.CreateQueueAsync(request); Console.WriteLine($"Created a queue with URL : {response.QueueUrl}"); return response; } /// <summary> /// Sends a message to an SQS queue. /// </summary> /// <param name="client">An SQS client object used to send the message.</ param> /// <param name="queueUrl">The URL of the queue to which to send the /// message.</param> /// <param name="messageBody">A string representing the body of the /// message to be sent to the queue.</param> /// <param name="messageAttributes">Attributes for the message to be /// sent to the queue.</param> /// <returns>A SendMessageResponse object that contains information /// about the message that was sent.</returns> public static async Task<SendMessageResponse> SendMessage( IAmazonSQS client, string queueUrl, string messageBody, Dictionary<string, MessageAttributeValue> messageAttributes) { var sendMessageRequest = new SendMessageRequest { DelaySeconds = 10, MessageAttributes = messageAttributes, MessageBody = messageBody, QueueUrl = queueUrl, }; var response = await client.SendMessageAsync(sendMessageRequest); Console.WriteLine($"Sent a message with id : {response.MessageId}"); return response; } Actions
|
sqs-dg-082
|
sqs-dg.pdf
| 82 |
which to send the /// message.</param> /// <param name="messageBody">A string representing the body of the /// message to be sent to the queue.</param> /// <param name="messageAttributes">Attributes for the message to be /// sent to the queue.</param> /// <returns>A SendMessageResponse object that contains information /// about the message that was sent.</returns> public static async Task<SendMessageResponse> SendMessage( IAmazonSQS client, string queueUrl, string messageBody, Dictionary<string, MessageAttributeValue> messageAttributes) { var sendMessageRequest = new SendMessageRequest { DelaySeconds = 10, MessageAttributes = messageAttributes, MessageBody = messageBody, QueueUrl = queueUrl, }; var response = await client.SendMessageAsync(sendMessageRequest); Console.WriteLine($"Sent a message with id : {response.MessageId}"); return response; } Actions 266 Amazon Simple Queue Service } Developer Guide • For API details, see CreateQueue in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Create an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueName: An Amazon SQS queue name. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::createQueue(const Aws::String &queueName, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::CreateQueueRequest request; request.SetQueueName(queueName); const Aws::SQS::Model::CreateQueueOutcome outcome = sqsClient.CreateQueue(request); if (outcome.IsSuccess()) { std::cout << "Successfully created queue " << queueName << " with a queue URL " << outcome.GetResult().GetQueueUrl() << "." << std::endl; } else { Actions 267 Amazon Simple Queue Service Developer Guide std::cerr << "Error creating queue " << queueName << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see CreateQueue in AWS SDK for C++ API Reference. CLI AWS CLI To create a queue This example creates a queue with the specified name, sets the message retention period to 3 days (3 days * 24 hours * 60 minutes * 60 seconds), and sets the queue's dead letter queue to the specified queue with a maximum receive count of 1,000 messages. Command: aws sqs create-queue --queue-name MyQueue --attributes file://create-queue.json Input file (create-queue.json): { "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us- east-1:80398EXAMPLE:MyDeadLetterQueue\",\"maxReceiveCount\":\"1000\"}", "MessageRetentionPeriod": "259200" } Output: { "QueueUrl": "https://queue.amazonaws.com/80398EXAMPLE/MyQueue" } • For API details, see CreateQueue in AWS CLI Command Reference. Actions 268 Amazon Simple Queue Service Go SDK for Go V2 Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import ( "context" "encoding/json" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" ) // SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions // used in the examples. type SqsActions struct { SqsClient *sqs.Client } // CreateQueue creates an Amazon SQS queue with the specified name. You can specify // whether the queue is created as a FIFO queue. func (actor SqsActions) CreateQueue(ctx context.Context, queueName string, isFifoQueue bool) (string, error) { var queueUrl string queueAttributes := map[string]string{} if isFifoQueue { queueAttributes["FifoQueue"] = "true" } queue, err := actor.SqsClient.CreateQueue(ctx, &sqs.CreateQueueInput{ QueueName: aws.String(queueName), Actions 269 Amazon Simple Queue Service Developer Guide Attributes: queueAttributes, }) if err != nil { log.Printf("Couldn't create queue %v. Here's why: %v\n", queueName, err) } else { queueUrl = *queue.QueueUrl } return queueUrl, err } • For API details, see CreateQueue in AWS SDK for Go API Reference. 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. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.ChangeMessageVisibilityRequest; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.DeleteMessageRequest; import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest; import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse; import software.amazon.awssdk.services.sqs.model.ListQueuesRequest; import software.amazon.awssdk.services.sqs.model.ListQueuesResponse; import software.amazon.awssdk.services.sqs.model.Message; 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.SendMessageRequest; import software.amazon.awssdk.services.sqs.model.SqsException; import java.util.List; Actions 270 Amazon Simple Queue Service /** Developer Guide * 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 */ public class SQSExample { public static void main(String[] args) { String queueName = "queue" + System.currentTimeMillis(); SqsClient sqsClient = SqsClient.builder() .region(Region.US_WEST_2) .build(); // Perform various tasks on the Amazon SQS queue. String queueUrl = createQueue(sqsClient, queueName); listQueues(sqsClient); listQueuesFilter(sqsClient, queueUrl); List<Message> messages = receiveMessages(sqsClient, queueUrl); sendBatchMessages(sqsClient, queueUrl); changeMessages(sqsClient, queueUrl, messages); deleteMessages(sqsClient, queueUrl, messages); sqsClient.close(); } public static String createQueue(SqsClient sqsClient, String queueName) { try { System.out.println("\nCreate Queue"); CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .build(); sqsClient.createQueue(createQueueRequest); System.out.println("\nGet queue url"); GetQueueUrlResponse getQueueUrlResponse = sqsClient .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()); return getQueueUrlResponse.queueUrl(); Actions 271 Amazon Simple Queue Service Developer Guide } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static void listQueues(SqsClient sqsClient) { System.out.println("\nList Queues"); String prefix = "que"; try { ListQueuesRequest listQueuesRequest = ListQueuesRequest.builder().queueNamePrefix(prefix).build(); ListQueuesResponse listQueuesResponse = sqsClient.listQueues(listQueuesRequest); for (String url : listQueuesResponse.queueUrls()) { System.out.println(url); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void listQueuesFilter(SqsClient sqsClient, String queueUrl) { // List queues with filters String namePrefix = "queue"; ListQueuesRequest filterListRequest
|
sqs-dg-083
|
sqs-dg.pdf
| 83 |
queueName) { try { System.out.println("\nCreate Queue"); CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .build(); sqsClient.createQueue(createQueueRequest); System.out.println("\nGet queue url"); GetQueueUrlResponse getQueueUrlResponse = sqsClient .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()); return getQueueUrlResponse.queueUrl(); Actions 271 Amazon Simple Queue Service Developer Guide } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static void listQueues(SqsClient sqsClient) { System.out.println("\nList Queues"); String prefix = "que"; try { ListQueuesRequest listQueuesRequest = ListQueuesRequest.builder().queueNamePrefix(prefix).build(); ListQueuesResponse listQueuesResponse = sqsClient.listQueues(listQueuesRequest); for (String url : listQueuesResponse.queueUrls()) { System.out.println(url); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void listQueuesFilter(SqsClient sqsClient, String queueUrl) { // List queues with filters String namePrefix = "queue"; ListQueuesRequest filterListRequest = ListQueuesRequest.builder() .queueNamePrefix(namePrefix) .build(); ListQueuesResponse listQueuesFilteredResponse = sqsClient.listQueues(filterListRequest); System.out.println("Queue URLs with prefix: " + namePrefix); for (String url : listQueuesFilteredResponse.queueUrls()) { System.out.println(url); } System.out.println("\nSend message"); try { sqsClient.sendMessage(SendMessageRequest.builder() Actions 272 Amazon Simple Queue Service Developer Guide .queueUrl(queueUrl) .messageBody("Hello world!") .delaySeconds(10) .build()); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void sendBatchMessages(SqsClient sqsClient, String queueUrl) { System.out.println("\nSend multiple messages"); try { SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(SendMessageBatchRequestEntry.builder().id("id1").messageBody("Hello from msg 1").build(), SendMessageBatchRequestEntry.builder().id("id2").messageBody("msg 2").delaySeconds(10) .build()) .build(); sqsClient.sendMessageBatch(sendMessageBatchRequest); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static List<Message> receiveMessages(SqsClient sqsClient, String queueUrl) { System.out.println("\nReceive messages"); try { ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder() .queueUrl(queueUrl) .maxNumberOfMessages(5) .build(); Actions 273 Amazon Simple Queue Service Developer Guide return sqsClient.receiveMessage(receiveMessageRequest).messages(); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; } public static void changeMessages(SqsClient sqsClient, String queueUrl, List<Message> messages) { System.out.println("\nChange Message Visibility"); try { for (Message message : messages) { ChangeMessageVisibilityRequest req = ChangeMessageVisibilityRequest.builder() .queueUrl(queueUrl) .receiptHandle(message.receiptHandle()) .visibilityTimeout(100) .build(); sqsClient.changeMessageVisibility(req); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void deleteMessages(SqsClient sqsClient, String queueUrl, List<Message> messages) { System.out.println("\nDelete Messages"); try { for (Message message : messages) { DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder() .queueUrl(queueUrl) .receiptHandle(message.receiptHandle()) .build(); sqsClient.deleteMessage(deleteMessageRequest); } Actions 274 Amazon Simple Queue Service Developer Guide } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see CreateQueue in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create an Amazon SQS standard queue. import { CreateQueueCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_NAME = "test-queue"; export const main = async (sqsQueueName = SQS_QUEUE_NAME) => { const command = new CreateQueueCommand({ QueueName: sqsQueueName, Attributes: { DelaySeconds: "60", MessageRetentionPeriod: "86400", }, }); const response = await client.send(command); console.log(response); return response; }; Actions 275 Amazon Simple Queue Service Developer Guide Create an Amazon SQS queue with long polling. import { CreateQueueCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_NAME = "queue_name"; export const main = async (queueName = SQS_QUEUE_NAME) => { const response = await client.send( new CreateQueueCommand({ QueueName: queueName, Attributes: { // When the wait time for the ReceiveMessage API action is greater than 0, // long polling is in effect. The maximum long polling wait time is 20 // seconds. Long polling helps reduce the cost of using Amazon SQS by, // eliminating the number of empty responses and false empty responses. // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/ SQSDeveloperGuide/sqs-short-and-long-polling.html ReceiveMessageWaitTimeSeconds: "20", }, }), ); console.log(response); return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see CreateQueue in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create an Amazon SQS standard queue. // Load the AWS SDK for Node.js Actions 276 Amazon Simple Queue Service Developer Guide var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create an SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { QueueName: "SQS_QUEUE_NAME", Attributes: { DelaySeconds: "60", MessageRetentionPeriod: "86400", }, }; sqs.createQueue(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.QueueUrl); } }); Create an Amazon SQS queue that waits for a message to arrive. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { QueueName: "SQS_QUEUE_NAME", Attributes: { ReceiveMessageWaitTimeSeconds: "20", }, }; sqs.createQueue(params, function (err, data) { if (err) { Actions 277 Amazon Simple Queue Service Developer Guide console.log("Error", err); } else { console.log("Success", data.QueueUrl); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see CreateQueue in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun createQueue(queueNameVal: String): String { println("Create Queue") val createQueueRequest
|
sqs-dg-084
|
sqs-dg.pdf
| 84 |
"2012-11-05" }); var params = { QueueName: "SQS_QUEUE_NAME", Attributes: { ReceiveMessageWaitTimeSeconds: "20", }, }; sqs.createQueue(params, function (err, data) { if (err) { Actions 277 Amazon Simple Queue Service Developer Guide console.log("Error", err); } else { console.log("Success", data.QueueUrl); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see CreateQueue in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun createQueue(queueNameVal: String): String { println("Create Queue") val createQueueRequest = CreateQueueRequest { queueName = queueNameVal } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.createQueue(createQueueRequest) println("Get queue url") val getQueueUrlRequest = GetQueueUrlRequest { queueName = queueNameVal } val getQueueUrlResponse = sqsClient.getQueueUrl(getQueueUrlRequest) return getQueueUrlResponse.queueUrl.toString() } } Actions 278 Amazon Simple Queue Service Developer Guide • For API details, see CreateQueue in AWS SDK for Kotlin API reference. PowerShell Tools for PowerShell Example 1: This example creates a queue with the specified name. New-SQSQueue -QueueName MyQueue Output: https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue • For API details, see CreateQueue in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. def create_queue(name, attributes=None): """ Creates an Amazon SQS queue. :param name: The name of the queue. This is part of the URL assigned to the queue. :param attributes: The attributes of the queue, such as maximum message size or whether it's a FIFO queue. :return: A Queue object that contains metadata about the queue and that can be used to perform queue operations like sending and receiving messages. """ if not attributes: Actions 279 Amazon Simple Queue Service Developer Guide attributes = {} try: queue = sqs.create_queue(QueueName=name, Attributes=attributes) logger.info("Created queue '%s' with URL=%s", name, queue.url) except ClientError as error: logger.exception("Couldn't create queue named '%s'.", name) raise error else: return queue • For API details, see CreateQueue in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. # This code example demonstrates how to create a queue in Amazon Simple Queue Service (Amazon SQS). require 'aws-sdk-sqs' # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_name [String] The name of the queue. # @return [Boolean] true if the queue was created; otherwise, false. # @example # exit 1 unless queue_created?( # Aws::SQS::Client.new(region: 'us-west-2'), # 'my-queue' # ) def queue_created?(sqs_client, queue_name) sqs_client.create_queue(queue_name: queue_name) true Actions 280 Amazon Simple Queue Service Developer Guide rescue StandardError => e puts "Error creating queue: #{e.message}" false end # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me region = 'us-west-2' queue_name = 'my-queue' sqs_client = Aws::SQS::Client.new(region: region) puts "Creating the queue named '#{queue_name}'..." if queue_created?(sqs_client, queue_name) puts 'Queue created.' else puts 'Queue not created.' end end # Example usage: run_me if $PROGRAM_NAME == __FILE__ • For API details, see CreateQueue in AWS SDK for Ruby API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create an Amazon SQS standard queue. TRY. oo_result = lo_sqs->createqueue( iv_queuename = iv_queue_name ). " oo_result is returned for testing purposes. " Actions 281 Amazon Simple Queue Service Developer Guide MESSAGE 'SQS queue created.' TYPE 'I'. CATCH /aws1/cx_sqsqueuedeldrecently. MESSAGE 'After deleting a queue, wait 60 seconds before creating another queue with the same name.' TYPE 'E'. CATCH /aws1/cx_sqsqueuenameexists. MESSAGE 'A queue with this name already exists.' TYPE 'E'. ENDTRY. Create an Amazon SQS queue that waits for a message to arrive. TRY. DATA lt_attributes TYPE /aws1/cl_sqsqueueattrmap_w=>tt_queueattributemap. DATA ls_attribute TYPE /aws1/ cl_sqsqueueattrmap_w=>ts_queueattributemap_maprow. ls_attribute-key = 'ReceiveMessageWaitTimeSeconds'. " Time in seconds for long polling, such as how long the call waits for a message to arrive in the queue before returning. " ls_attribute-value = NEW /aws1/cl_sqsqueueattrmap_w( iv_value = iv_wait_time ). INSERT ls_attribute INTO TABLE lt_attributes. oo_result = lo_sqs->createqueue( " oo_result is returned for testing purposes. " iv_queuename = iv_queue_name it_attributes = lt_attributes ). MESSAGE 'SQS queue created.' TYPE 'I'. CATCH /aws1/cx_sqsqueuedeldrecently. MESSAGE 'After deleting a queue, wait 60 seconds before creating another queue with the same name.' TYPE 'E'. CATCH /aws1/cx_sqsqueuenameexists. MESSAGE 'A queue with this name already exists.' TYPE 'E'. ENDTRY. • For API details, see CreateQueue in AWS SDK for SAP ABAP API reference. Actions 282 Amazon Simple Queue Service Swift SDK for Swift Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSQS let config = try await SQSClient.SQSClientConfiguration(region:
|
sqs-dg-085
|
sqs-dg.pdf
| 85 |
it_attributes = lt_attributes ). MESSAGE 'SQS queue created.' TYPE 'I'. CATCH /aws1/cx_sqsqueuedeldrecently. MESSAGE 'After deleting a queue, wait 60 seconds before creating another queue with the same name.' TYPE 'E'. CATCH /aws1/cx_sqsqueuenameexists. MESSAGE 'A queue with this name already exists.' TYPE 'E'. ENDTRY. • For API details, see CreateQueue in AWS SDK for SAP ABAP API reference. Actions 282 Amazon Simple Queue Service Swift SDK for Swift Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSQS let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) let output = try await sqsClient.createQueue( input: CreateQueueInput( queueName: queueName ) ) guard let queueUrl = output.queueUrl else { print("No queue URL returned.") return } • For API details, see CreateQueue in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteMessage with an AWS SDK or CLI The following code examples show how to use DeleteMessage. Actions 283 Amazon Simple Queue Service .NET SDK for .NET Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Receive a message from an Amazon SQS queue and then delete the message. public static async Task Main() { // If the AWS Region you want to use is different from // the AWS Region defined for the default user, supply // the specify your AWS Region to the client constructor. var client = new AmazonSQSClient(); string queueName = "Example_Queue"; var queueUrl = await GetQueueUrl(client, queueName); Console.WriteLine($"The SQS queue's URL is {queueUrl}"); var response = await ReceiveAndDeleteMessage(client, queueUrl); Console.WriteLine($"Message: {response.Messages[0]}"); } /// <summary> /// Retrieve the queue URL for the queue named in the queueName /// property using the client object. /// </summary> /// <param name="client">The Amazon SQS client used to retrieve the /// queue URL.</param> /// <param name="queueName">A string representing name of the queue /// for which to retrieve the URL.</param> /// <returns>The URL of the queue.</returns> public static async Task<string> GetQueueUrl(IAmazonSQS client, string queueName) { var request = new GetQueueUrlRequest { QueueName = queueName, Actions 284 Amazon Simple Queue Service }; Developer Guide GetQueueUrlResponse response = await client.GetQueueUrlAsync(request); return response.QueueUrl; } /// <summary> /// Retrieves the message from the quque at the URL passed in the /// queueURL parameters using the client. /// </summary> /// <param name="client">The SQS client used to retrieve a message.</ param> /// <param name="queueUrl">The URL of the queue from which to retrieve /// a message.</param> /// <returns>The response from the call to ReceiveMessageAsync.</returns> public static async Task<ReceiveMessageResponse> ReceiveAndDeleteMessage(IAmazonSQS client, string queueUrl) { // Receive a single message from the queue. var receiveMessageRequest = new ReceiveMessageRequest { AttributeNames = { "SentTimestamp" }, MaxNumberOfMessages = 1, MessageAttributeNames = { "All" }, QueueUrl = queueUrl, VisibilityTimeout = 0, WaitTimeSeconds = 0, }; var receiveMessageResponse = await client.ReceiveMessageAsync(receiveMessageRequest); // Delete the received message from the queue. var deleteMessageRequest = new DeleteMessageRequest { QueueUrl = queueUrl, ReceiptHandle = receiveMessageResponse.Messages[0].ReceiptHandle, }; await client.DeleteMessageAsync(deleteMessageRequest); return receiveMessageResponse; } Actions 285 Amazon Simple Queue Service } Developer Guide • For API details, see DeleteMessage in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Delete a message from an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. \param messageReceiptHandle: A message receipt handle. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::deleteMessage(const Aws::String &queueUrl, const Aws::String &messageReceiptHandle, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::DeleteMessageRequest request; request.SetQueueUrl(queueUrl); request.SetReceiptHandle(messageReceiptHandle); const Aws::SQS::Model::DeleteMessageOutcome outcome = sqsClient.DeleteMessage( request); if (outcome.IsSuccess()) { std::cout << "Successfully deleted message from queue " << queueUrl Actions 286 Amazon Simple Queue Service Developer Guide << std::endl; } else { std::cerr << "Error deleting message from queue " << queueUrl << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see DeleteMessage in AWS SDK for C++ API Reference. CLI AWS CLI To delete a message This example deletes the specified message. Command: aws sqs delete-message --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --receipt-handle AQEBRXTo...q2doVA== Output: None. • For API details, see DeleteMessage in AWS CLI Command Reference. 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. Actions 287 Amazon Simple Queue Service Developer Guide try { for (Message message : messages) {
|
sqs-dg-086
|
sqs-dg.pdf
| 86 |
<< outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see DeleteMessage in AWS SDK for C++ API Reference. CLI AWS CLI To delete a message This example deletes the specified message. Command: aws sqs delete-message --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --receipt-handle AQEBRXTo...q2doVA== Output: None. • For API details, see DeleteMessage in AWS CLI Command Reference. 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. Actions 287 Amazon Simple Queue Service Developer Guide try { for (Message message : messages) { DeleteMessageRequest deleteMessageRequest = DeleteMessageRequest.builder() .queueUrl(queueUrl) .receiptHandle(message.receiptHandle()) .build(); sqsClient.deleteMessage(deleteMessageRequest); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } • For API details, see DeleteMessage in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Receive and delete Amazon SQS messages. import { ReceiveMessageCommand, DeleteMessageCommand, SQSClient, DeleteMessageBatchCommand, } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; const receiveMessage = (queueUrl) => client.send( Actions 288 Amazon Simple Queue Service Developer Guide new ReceiveMessageCommand({ AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 10, MessageAttributeNames: ["All"], QueueUrl: queueUrl, WaitTimeSeconds: 20, VisibilityTimeout: 20, }), ); export const main = async (queueUrl = SQS_QUEUE_URL) => { const { Messages } = await receiveMessage(queueUrl); if (!Messages) { return; } if (Messages.length === 1) { console.log(Messages[0].Body); await client.send( new DeleteMessageCommand({ QueueUrl: queueUrl, ReceiptHandle: Messages[0].ReceiptHandle, }), ); } else { await client.send( new DeleteMessageBatchCommand({ QueueUrl: queueUrl, Entries: Messages.map((message) => ({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle, })), }), ); } }; • For API details, see DeleteMessage in AWS SDK for JavaScript API Reference. Actions 289 Amazon Simple Queue Service SDK for JavaScript (v2) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Receive and delete Amazon SQS messages. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create an SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var queueURL = "SQS_QUEUE_URL"; var params = { AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 10, MessageAttributeNames: ["All"], QueueUrl: queueURL, VisibilityTimeout: 20, WaitTimeSeconds: 0, }; sqs.receiveMessage(params, function (err, data) { if (err) { console.log("Receive Error", err); } else if (data.Messages) { var deleteParams = { QueueUrl: queueURL, ReceiptHandle: data.Messages[0].ReceiptHandle, }; sqs.deleteMessage(deleteParams, function (err, data) { if (err) { console.log("Delete Error", err); } else { console.log("Message Deleted", data); } Actions 290 Amazon Simple Queue Service Developer Guide }); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DeleteMessage in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun deleteMessages(queueUrlVal: String) { println("Delete Messages from $queueUrlVal") val purgeRequest = PurgeQueueRequest { queueUrl = queueUrlVal } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.purgeQueue(purgeRequest) println("Messages are successfully deleted from $queueUrlVal") } } suspend fun deleteQueue(queueUrlVal: String) { val request = DeleteQueueRequest { queueUrl = queueUrlVal } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.deleteQueue(request) println("$queueUrlVal was deleted!") Actions 291 Amazon Simple Queue Service Developer Guide } } • For API details, see DeleteMessage in AWS SDK for Kotlin API reference. PowerShell Tools for PowerShell Example 1: This example deletes the message with the specified receipt handle from the specified queue. Remove-SQSMessage -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/ MyQueue -ReceiptHandle AQEBd329...v6gl8Q== • For API details, see DeleteMessage in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. def delete_message(message): """ Delete a message from a queue. Clients must delete messages after they are received and processed to remove them from the queue. :param message: The message to delete. The message's queue URL is contained in the message's metadata. :return: None """ try: message.delete() Actions 292 Amazon Simple Queue Service Developer Guide logger.info("Deleted message: %s", message.message_id) except ClientError as error: logger.exception("Couldn't delete message: %s", message.message_id) raise error • For API details, see DeleteMessage in AWS SDK for Python (Boto3) API Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteMessageBatch with an AWS SDK or CLI The following code examples show how to use DeleteMessageBatch. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: •
|
sqs-dg-087
|
sqs-dg.pdf
| 87 |
error: logger.exception("Couldn't delete message: %s", message.message_id) raise error • For API details, see DeleteMessage in AWS SDK for Python (Boto3) API Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteMessageBatch with an AWS SDK or CLI The following code examples show how to use DeleteMessageBatch. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Process S3 event notifications • Publish messages to queues • Send and receive batches of messages .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Delete a batch of messages from a queue by its url. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>True if successful.</returns> Actions 293 Amazon Simple Queue Service Developer Guide public async Task<bool> DeleteMessageBatchByUrl(string queueUrl, List<Message> messages) { var deleteRequest = new DeleteMessageBatchRequest() { QueueUrl = queueUrl, Entries = new List<DeleteMessageBatchRequestEntry>() }; foreach (var message in messages) { deleteRequest.Entries.Add(new DeleteMessageBatchRequestEntry() { ReceiptHandle = message.ReceiptHandle, Id = message.MessageId }); } var deleteResponse = await _amazonSQSClient.DeleteMessageBatchAsync(deleteRequest); return deleteResponse.Failed.Any(); } • For API details, see DeleteMessageBatch in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SQS::SQSClient sqsClient(clientConfiguration); Actions 294 Amazon Simple Queue Service Developer Guide Aws::SQS::Model::DeleteMessageBatchRequest request; request.SetQueueUrl(queueURLS[i]); int id = 1; // Ids must be unique within a batch delete request. for (const Aws::String &receiptHandle: receiptHandles) { Aws::SQS::Model::DeleteMessageBatchRequestEntry entry; entry.SetId(std::to_string(id)); ++id; entry.SetReceiptHandle(receiptHandle); request.AddEntries(entry); } Aws::SQS::Model::DeleteMessageBatchOutcome outcome = sqsClient.DeleteMessageBatch(request); if (outcome.IsSuccess()) { std::cout << "The batch deletion of messages was successful." << std::endl; } else { std::cerr << "Error with SQS::DeleteMessageBatch. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } • For API details, see DeleteMessageBatch in AWS SDK for C++ API Reference. CLI AWS CLI To delete multiple messages as a batch This example deletes the specified messages. Command: Actions 295 Amazon Simple Queue Service Developer Guide aws sqs delete-message-batch --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --entries file://delete-message- batch.json Input file (delete-message-batch.json): [ { "Id": "FirstMessage", "ReceiptHandle": "AQEB1mgl...Z4GuLw==" }, { "Id": "SecondMessage", "ReceiptHandle": "AQEBLsYM...VQubAA==" } ] Output: { "Successful": [ { "Id": "FirstMessage" }, { "Id": "SecondMessage" } ] } • For API details, see DeleteMessageBatch in AWS CLI Command Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 296 Amazon Simple Queue Service Developer Guide import ( "context" "encoding/json" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" ) // SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions // used in the examples. type SqsActions struct { SqsClient *sqs.Client } // DeleteMessages uses the DeleteMessageBatch action to delete a batch of messages from // an Amazon SQS queue. func (actor SqsActions) DeleteMessages(ctx context.Context, queueUrl string, messages []types.Message) error { entries := make([]types.DeleteMessageBatchRequestEntry, len(messages)) for msgIndex := range messages { entries[msgIndex].Id = aws.String(fmt.Sprintf("%v", msgIndex)) entries[msgIndex].ReceiptHandle = messages[msgIndex].ReceiptHandle } _, err := actor.SqsClient.DeleteMessageBatch(ctx, &sqs.DeleteMessageBatchInput{ Entries: entries, QueueUrl: aws.String(queueUrl), }) if err != nil { log.Printf("Couldn't delete messages from queue %v. Here's why: %v\n", queueUrl, err) } return err } Actions 297 Amazon Simple Queue Service Developer Guide • For API details, see DeleteMessageBatch in AWS SDK for Go API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { ReceiveMessageCommand, DeleteMessageCommand, SQSClient, DeleteMessageBatchCommand, } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; const receiveMessage = (queueUrl) => client.send( new ReceiveMessageCommand({ AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 10, MessageAttributeNames: ["All"], QueueUrl: queueUrl, WaitTimeSeconds: 20, VisibilityTimeout: 20, }), ); export const main = async (queueUrl = SQS_QUEUE_URL) => { const { Messages } = await receiveMessage(queueUrl); if (!Messages) { return; } if (Messages.length === 1) { Actions 298 Amazon Simple Queue Service Developer Guide console.log(Messages[0].Body); await client.send( new DeleteMessageCommand({ QueueUrl: queueUrl, ReceiptHandle: Messages[0].ReceiptHandle, }), ); } else { await client.send( new DeleteMessageBatchCommand({ QueueUrl: queueUrl, Entries: Messages.map((message) => ({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle, })), }), ); } }; • For API details, see DeleteMessageBatch in AWS SDK for JavaScript API Reference. PowerShell Tools for PowerShell Example 1: This example deletes 2 messages with the specified receipt handles from the specified queue. $deleteMessageRequest1 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry $deleteMessageRequest1.Id = "Request1" $deleteMessageRequest1.ReceiptHandle = "AQEBX2g4...wtJSQg==" $deleteMessageRequest2 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry $deleteMessageRequest2.Id
|
sqs-dg-088
|
sqs-dg.pdf
| 88 |
receiveMessage(queueUrl); if (!Messages) { return; } if (Messages.length === 1) { Actions 298 Amazon Simple Queue Service Developer Guide console.log(Messages[0].Body); await client.send( new DeleteMessageCommand({ QueueUrl: queueUrl, ReceiptHandle: Messages[0].ReceiptHandle, }), ); } else { await client.send( new DeleteMessageBatchCommand({ QueueUrl: queueUrl, Entries: Messages.map((message) => ({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle, })), }), ); } }; • For API details, see DeleteMessageBatch in AWS SDK for JavaScript API Reference. PowerShell Tools for PowerShell Example 1: This example deletes 2 messages with the specified receipt handles from the specified queue. $deleteMessageRequest1 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry $deleteMessageRequest1.Id = "Request1" $deleteMessageRequest1.ReceiptHandle = "AQEBX2g4...wtJSQg==" $deleteMessageRequest2 = New-Object Amazon.SQS.Model.DeleteMessageBatchRequestEntry $deleteMessageRequest2.Id = "Request2" $deleteMessageRequest2.ReceiptHandle = "AQEBqOVY...KTsLYg==" Actions 299 Amazon Simple Queue Service Developer Guide Remove-SQSMessageBatch -QueueUrl https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue -Entry $deleteMessageRequest1, $deleteMessageRequest2 Output: Failed Successful ------ ---------- {} {Request1, Request2} • For API details, see DeleteMessageBatch in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. def delete_messages(queue, messages): """ Delete a batch of messages from a queue in a single request. :param queue: 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. """ try: entries = [ {"Id": str(ind), "ReceiptHandle": msg.receipt_handle} for ind, msg in enumerate(messages) ] response = queue.delete_messages(Entries=entries) if "Successful" in response: Actions 300 Amazon Simple Queue Service Developer Guide for msg_meta in response["Successful"]: logger.info("Deleted %s", messages[int(msg_meta["Id"])].receipt_handle) if "Failed" in response: for msg_meta in response["Failed"]: logger.warning( "Could not delete %s", messages[int(msg_meta["Id"])].receipt_handle ) except ClientError: logger.exception("Couldn't delete messages from queue %s", queue) else: return response • For API details, see DeleteMessageBatch in AWS SDK for Python (Boto3) API Reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSQS let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) // Create the list of message entries. var entries: [SQSClientTypes.DeleteMessageBatchRequestEntry] = [] var messageNumber = 1 for handle in handles { let entry = SQSClientTypes.DeleteMessageBatchRequestEntry( id: "\(messageNumber)", Actions 301 Amazon Simple Queue Service Developer Guide receiptHandle: handle ) entries.append(entry) messageNumber += 1 } // Delete the messages. let output = try await sqsClient.deleteMessageBatch( input: DeleteMessageBatchInput( entries: entries, queueUrl: queue ) ) // Get the lists of failed and successful deletions from the output. guard let failedEntries = output.failed else { print("Failed deletion list is missing!") return } guard let successfulEntries = output.successful else { print("Successful deletion list is missing!") return } // Display a list of the failed deletions along with their // corresponding explanation messages. if failedEntries.count != 0 { print("Failed deletions:") for entry in failedEntries { print("Message #\(entry.id ?? "<unknown>") failed: \(entry.message ?? "<unknown>")") } } else { print("No failed deletions.") } // Output a list of the message numbers that were successfully deleted. if successfulEntries.count != 0 { var successes = "" Actions 302 Amazon Simple Queue Service Developer Guide for entry in successfulEntries { if successes.count == 0 { successes = entry.id ?? "<unknown>" } else { successes = "\(successes), \(entry.id ?? "<unknown>")" } } print("Succeeded: ", successes) } else { print("No successful deletions.") } • For API details, see DeleteMessageBatch in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use DeleteQueue with an AWS SDK or CLI The following code examples show how to use DeleteQueue. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Publish messages to queues • Send and receive batches of messages • Use the Amazon SQS Java Messaging Library to work with the JMS interface .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 303 Amazon Simple Queue Service Developer Guide Delete a queue by using its URL. /// <summary> /// Delete a queue by its URL. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteQueueByUrl(string queueUrl) { var deleteResponse = await _amazonSQSClient.DeleteQueueAsync( new DeleteQueueRequest() { QueueUrl = queueUrl }); return deleteResponse.HttpStatusCode == HttpStatusCode.OK; } • For API details, see DeleteQueue in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config
|
sqs-dg-089
|
sqs-dg.pdf
| 89 |
by using its URL. /// <summary> /// Delete a queue by its URL. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteQueueByUrl(string queueUrl) { var deleteResponse = await _amazonSQSClient.DeleteQueueAsync( new DeleteQueueRequest() { QueueUrl = queueUrl }); return deleteResponse.HttpStatusCode == HttpStatusCode.OK; } • For API details, see DeleteQueue in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Delete an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueURL: An Amazon SQS queue URL. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::deleteQueue(const Aws::String &queueURL, Actions 304 Amazon Simple Queue Service Developer Guide const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::DeleteQueueRequest request; request.SetQueueUrl(queueURL); const Aws::SQS::Model::DeleteQueueOutcome outcome = sqsClient.DeleteQueue(request); if (outcome.IsSuccess()) { std::cout << "Successfully deleted queue with url " << queueURL << std::endl; } else { std::cerr << "Error deleting queue " << queueURL << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see DeleteQueue in AWS SDK for C++ API Reference. CLI AWS CLI To delete a queue This example deletes the specified queue. Command: aws sqs delete-queue --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyNewerQueue Output: None. • For API details, see DeleteQueue in AWS CLI Command Reference. Actions 305 Amazon Simple Queue Service Go SDK for Go V2 Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import ( "context" "encoding/json" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" ) // SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions // used in the examples. type SqsActions struct { SqsClient *sqs.Client } // DeleteQueue deletes an Amazon SQS queue. func (actor SqsActions) DeleteQueue(ctx context.Context, queueUrl string) error { _, err := actor.SqsClient.DeleteQueue(ctx, &sqs.DeleteQueueInput{ QueueUrl: aws.String(queueUrl)}) if err != nil { log.Printf("Couldn't delete queue %v. Here's why: %v\n", queueUrl, err) } return err } Actions 306 Amazon Simple Queue Service Developer Guide • For API details, see DeleteQueue in AWS SDK for Go API Reference. 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. import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest; import software.amazon.awssdk.services.sqs.model.DeleteQueueRequest; import software.amazon.awssdk.services.sqs.model.SqsException; /** * 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 */ public class DeleteQueue { public static void main(String[] args) { final String usage = """ Usage: <queueName> Where: queueName - The name of the Amazon SQS queue to delete. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } Actions 307 Amazon Simple Queue Service Developer Guide String queueName = args[0]; SqsClient sqs = SqsClient.builder() .region(Region.US_WEST_2) .build(); deleteSQSQueue(sqs, queueName); sqs.close(); } public static void deleteSQSQueue(SqsClient sqsClient, String queueName) { try { GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder() .queueName(queueName) .build(); String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl(); DeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder() .queueUrl(queueUrl) .build(); sqsClient.deleteQueue(deleteQueueRequest); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } • For API details, see DeleteQueue in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 308 Amazon Simple Queue Service Developer Guide Delete an Amazon SQS queue. import { DeleteQueueCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "test-queue-url"; export const main = async (queueUrl = SQS_QUEUE_URL) => { const command = new DeleteQueueCommand({ QueueUrl: queueUrl }); const response = await client.send(command); console.log(response); return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DeleteQueue in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Delete an Amazon SQS queue. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create an SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { QueueUrl: "SQS_QUEUE_URL", }; sqs.deleteQueue(params, function (err, data) { Actions 309 Amazon Simple Queue Service if (err) { console.log("Error", err); } else { console.log("Success", data); } }); Developer Guide • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DeleteQueue in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how
|
sqs-dg-090
|
sqs-dg.pdf
| 90 |
for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create an SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { QueueUrl: "SQS_QUEUE_URL", }; sqs.deleteQueue(params, function (err, data) { Actions 309 Amazon Simple Queue Service if (err) { console.log("Error", err); } else { console.log("Success", data); } }); Developer Guide • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see DeleteQueue in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun deleteMessages(queueUrlVal: String) { println("Delete Messages from $queueUrlVal") val purgeRequest = PurgeQueueRequest { queueUrl = queueUrlVal } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.purgeQueue(purgeRequest) println("Messages are successfully deleted from $queueUrlVal") } } suspend fun deleteQueue(queueUrlVal: String) { val request = DeleteQueueRequest { queueUrl = queueUrlVal } Actions 310 Amazon Simple Queue Service Developer Guide SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.deleteQueue(request) println("$queueUrlVal was deleted!") } } • For API details, see DeleteQueue in AWS SDK for Kotlin API reference. PowerShell Tools for PowerShell Example 1: This example deletes the specified queue. Remove-SQSQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/ MyQueue • For API details, see DeleteQueue in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. def remove_queue(queue): """ Removes an SQS queue. When run against an AWS account, it can take up to 60 seconds before the queue is actually deleted. :param queue: The queue to delete. :return: None """ try: queue.delete() logger.info("Deleted queue with URL=%s.", queue.url) Actions 311 Amazon Simple Queue Service Developer Guide except ClientError as error: logger.exception("Couldn't delete queue with URL=%s!", queue.url) raise error • For API details, see DeleteQueue in AWS SDK for Python (Boto3) API Reference. Ruby SDK for Ruby Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'aws-sdk-sqs' # v2: require 'aws-sdk' # Replace us-west-2 with the AWS Region you're using for Amazon SQS. sqs = Aws::SQS::Client.new(region: 'us-west-2') sqs.delete_queue(queue_url: URL) • For API details, see DeleteQueue in AWS SDK for Ruby API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. Actions 312 Amazon Simple Queue Service Developer Guide lo_sqs->deletequeue( iv_queueurl = iv_queue_url ). MESSAGE 'SQS queue deleted' TYPE 'I'. ENDTRY. • For API details, see DeleteQueue in AWS SDK for SAP ABAP API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSQS let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) do { _ = try await sqsClient.deleteQueue( input: DeleteQueueInput( queueUrl: queueUrl ) ) } catch _ as AWSSQS.QueueDoesNotExist { print("Error: The specified queue doesn't exist.") return } • For API details, see DeleteQueue in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 313 Amazon Simple Queue Service Developer Guide Use GetQueueAttributes with an AWS SDK or CLI The following code examples show how to use GetQueueAttributes. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Process S3 event notifications • Publish messages to queues .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. /// <summary> /// Get the ARN for a queue from its URL. /// </summary> /// <param name="queueUrl">The URL of the queue.</param> /// <returns>The ARN of the queue.</returns> public async Task<string> GetQueueArnByUrl(string queueUrl) { var getAttributesRequest = new GetQueueAttributesRequest() { QueueUrl = queueUrl, AttributeNames = new List<string>() { QueueAttributeName.QueueArn } }; var getAttributesResponse = await _amazonSQSClient.GetQueueAttributesAsync( getAttributesRequest); return getAttributesResponse.QueueARN; } Actions 314 Amazon Simple Queue Service Developer Guide • For API details, see GetQueueAttributes in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::GetQueueAttributesRequest request; request.SetQueueUrl(queueURL); request.AddAttributeNames(Aws::SQS::Model::QueueAttributeName::QueueArn); Aws::SQS::Model::GetQueueAttributesOutcome outcome = sqsClient.GetQueueAttributes(request); if (outcome.IsSuccess()) { const Aws::Map<Aws::SQS::Model::QueueAttributeName, Aws::String>
|
sqs-dg-091
|
sqs-dg.pdf
| 91 |
QueueUrl = queueUrl, AttributeNames = new List<string>() { QueueAttributeName.QueueArn } }; var getAttributesResponse = await _amazonSQSClient.GetQueueAttributesAsync( getAttributesRequest); return getAttributesResponse.QueueARN; } Actions 314 Amazon Simple Queue Service Developer Guide • For API details, see GetQueueAttributes in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::GetQueueAttributesRequest request; request.SetQueueUrl(queueURL); request.AddAttributeNames(Aws::SQS::Model::QueueAttributeName::QueueArn); Aws::SQS::Model::GetQueueAttributesOutcome outcome = sqsClient.GetQueueAttributes(request); if (outcome.IsSuccess()) { const Aws::Map<Aws::SQS::Model::QueueAttributeName, Aws::String> &attributes = outcome.GetResult().GetAttributes(); const auto &iter = attributes.find( Aws::SQS::Model::QueueAttributeName::QueueArn); if (iter != attributes.end()) { queueARN = iter->second; std::cout << "The queue ARN '" << queueARN << "' has been retrieved." << std::endl; } } else { std::cerr << "Error with SQS::GetQueueAttributes. " Actions 315 Amazon Simple Queue Service Developer Guide << outcome.GetError().GetMessage() << std::endl; } • For API details, see GetQueueAttributes in AWS SDK for C++ API Reference. CLI AWS CLI To get a queue's attributes This example gets all of the specified queue's attributes. Command: aws sqs get-queue-attributes --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --attribute-names All Output: { "Attributes": { "ApproximateNumberOfMessagesNotVisible": "0", "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us- east-1:80398EXAMPLE:MyDeadLetterQueue\",\"maxReceiveCount\":1000}", "MessageRetentionPeriod": "345600", "ApproximateNumberOfMessagesDelayed": "0", "MaximumMessageSize": "262144", "CreatedTimestamp": "1442426968", "ApproximateNumberOfMessages": "0", "ReceiveMessageWaitTimeSeconds": "0", "DelaySeconds": "0", "VisibilityTimeout": "30", "LastModifiedTimestamp": "1442426968", "QueueArn": "arn:aws:sqs:us-east-1:80398EXAMPLE:MyNewQueue" } } Actions 316 Amazon Simple Queue Service Developer Guide This example gets only the specified queue's maximum message size and visibility timeout attributes. Command: aws sqs get-queue-attributes --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyNewQueue --attribute- names MaximumMessageSize VisibilityTimeout Output: { "Attributes": { "VisibilityTimeout": "30", "MaximumMessageSize": "262144" } } • For API details, see GetQueueAttributes in AWS CLI Command Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import ( "context" "encoding/json" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" Actions 317 Amazon Simple Queue Service ) Developer Guide // SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions // used in the examples. type SqsActions struct { SqsClient *sqs.Client } // GetQueueArn uses the GetQueueAttributes action to get the Amazon Resource Name (ARN) // of an Amazon SQS queue. func (actor SqsActions) GetQueueArn(ctx context.Context, queueUrl string) (string, error) { var queueArn string arnAttributeName := types.QueueAttributeNameQueueArn attribute, err := actor.SqsClient.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{ QueueUrl: aws.String(queueUrl), AttributeNames: []types.QueueAttributeName{arnAttributeName}, }) if err != nil { log.Printf("Couldn't get ARN for queue %v. Here's why: %v\n", queueUrl, err) } else { queueArn = attribute.Attributes[string(arnAttributeName)] } return queueArn, err } • For API details, see GetQueueAttributes in AWS SDK for Go API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 318 Amazon Simple Queue Service Developer Guide import { GetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue-url"; export const getQueueAttributes = async (queueUrl = SQS_QUEUE_URL) => { const command = new GetQueueAttributesCommand({ QueueUrl: queueUrl, AttributeNames: ["DelaySeconds"], }); const response = await client.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '747a1192-c334-5682-a508-4cd5e8dc4e79', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // Attributes: { DelaySeconds: '1' } // } return response; }; • For API details, see GetQueueAttributes in AWS SDK for JavaScript API Reference. PowerShell Tools for PowerShell Example 1: This example lists all attributes for the specified queue. Get-SQSQueueAttribute -AttributeName All -QueueUrl https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue Output: VisibilityTimeout : 30 Actions 319 Amazon Simple Queue Service Developer Guide DelaySeconds : 0 MaximumMessageSize : 262144 MessageRetentionPeriod : 345600 ApproximateNumberOfMessages : 0 ApproximateNumberOfMessagesNotVisible : 0 ApproximateNumberOfMessagesDelayed : 0 CreatedTimestamp : 2/11/2015 5:53:35 PM LastModifiedTimestamp : 12/29/2015 2:23:17 PM QueueARN : arn:aws:sqs:us- east-1:80398EXAMPLE:MyQueue Policy : {"Version":"2008-10-17","Id":"arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue/ SQSDefaultPolicy","Statement":[{"Sid":"Sid14 495134224EX","Effect":"Allow","Principal": {"AWS":"*"},"Action":"SQS:SendMessage","Resource":"arn:aws:sqs:us-east-1:80 398EXAMPLE:MyQueue","Condition": {"ArnEquals":{"aws:SourceArn":"arn:aws:sns:us-east-1:80398EXAMPLE:MyTopic"}}}, {"Sid": "SendMessagesFromMyQueue","Effect":"Allow","Principal": {"AWS":"80398EXAMPLE"},"Action":"SQS:SendMessage","Resource":" arn:aws:sqs:us- east-1:80398EXAMPLE:MyQueue"}]} Attributes : {[QueueArn, arn:aws:sqs:us- east-1:80398EXAMPLE:MyQueue], [ApproximateNumberOfMessages, 0], [ApproximateNumberOfMessagesNotVisible, 0], [ApproximateNumberOfMessagesDelayed, 0]...} Example 2: This example lists separately only the specified attributes for the specified queue. Get-SQSQueueAttribute -AttributeName MaximumMessageSize, VisibilityTimeout - QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue Output: VisibilityTimeout : 30 DelaySeconds : 0 MaximumMessageSize : 262144 MessageRetentionPeriod : 345600 ApproximateNumberOfMessages : 0 ApproximateNumberOfMessagesNotVisible : 0 Actions 320 Amazon Simple Queue Service Developer Guide ApproximateNumberOfMessagesDelayed : 0 CreatedTimestamp : 2/11/2015 5:53:35 PM LastModifiedTimestamp : 12/29/2015 2:23:17 PM QueueARN : arn:aws:sqs:us- east-1:80398EXAMPLE:MyQueue Policy : {"Version":"2008-10-17","Id":"arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue/ SQSDefaultPolicy","Statement":[{"Sid":"Sid14 495134224EX","Effect":"Allow","Principal": {"AWS":"*"},"Action":"SQS:SendMessage","Resource":"arn:aws:sqs:us-east-1:80 398EXAMPLE:MyQueue","Condition": {"ArnEquals":{"aws:SourceArn":"arn:aws:sns:us-east-1:80398EXAMPLE:MyTopic"}}}, {"Sid": "SendMessagesFromMyQueue","Effect":"Allow","Principal": {"AWS":"80398EXAMPLE"},"Action":"SQS:SendMessage","Resource":" arn:aws:sqs:us- east-1:80398EXAMPLE:MyQueue"}]} Attributes : {[MaximumMessageSize, 262144], [VisibilityTimeout, 30]} • For API details, see GetQueueAttributes in AWS Tools for PowerShell Cmdlet Reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSQS let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) let output = try await sqsClient.getQueueAttributes( input: GetQueueAttributesInput( attributeNames: [ Actions 321 Amazon
|
sqs-dg-092
|
sqs-dg.pdf
| 92 |
CreatedTimestamp : 2/11/2015 5:53:35 PM LastModifiedTimestamp : 12/29/2015 2:23:17 PM QueueARN : arn:aws:sqs:us- east-1:80398EXAMPLE:MyQueue Policy : {"Version":"2008-10-17","Id":"arn:aws:sqs:us-east-1:80398EXAMPLE:MyQueue/ SQSDefaultPolicy","Statement":[{"Sid":"Sid14 495134224EX","Effect":"Allow","Principal": {"AWS":"*"},"Action":"SQS:SendMessage","Resource":"arn:aws:sqs:us-east-1:80 398EXAMPLE:MyQueue","Condition": {"ArnEquals":{"aws:SourceArn":"arn:aws:sns:us-east-1:80398EXAMPLE:MyTopic"}}}, {"Sid": "SendMessagesFromMyQueue","Effect":"Allow","Principal": {"AWS":"80398EXAMPLE"},"Action":"SQS:SendMessage","Resource":" arn:aws:sqs:us- east-1:80398EXAMPLE:MyQueue"}]} Attributes : {[MaximumMessageSize, 262144], [VisibilityTimeout, 30]} • For API details, see GetQueueAttributes in AWS Tools for PowerShell Cmdlet Reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSQS let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) let output = try await sqsClient.getQueueAttributes( input: GetQueueAttributesInput( attributeNames: [ Actions 321 Amazon Simple Queue Service Developer Guide .approximatenumberofmessages, .maximummessagesize ], queueUrl: url ) ) guard let attributes = output.attributes else { print("No queue attributes returned.") return } for (attr, value) in attributes { switch(attr) { case "ApproximateNumberOfMessages": print("Approximate message count: \(value)") case "MaximumMessageSize": print("Maximum message size: \(value)kB") default: continue } } • For API details, see GetQueueAttributes in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use GetQueueUrl with an AWS SDK or CLI The following code examples show how to use GetQueueUrl. Actions 322 Amazon Simple Queue Service .NET SDK for .NET Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. using System; using System.Threading.Tasks; using Amazon.SQS; using Amazon.SQS.Model; public class GetQueueUrl { /// <summary> /// Initializes the Amazon SQS client object and then calls the /// GetQueueUrlAsync method to retrieve the URL of an Amazon SQS /// queue. /// </summary> public static async Task Main() { // If the Amazon SQS message queue is not in the same AWS Region as your // default user, you need to provide the AWS Region as a parameter to the // client constructor. var client = new AmazonSQSClient(); string queueName = "New-Example-Queue"; try { var response = await client.GetQueueUrlAsync(queueName); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { Console.WriteLine($"The URL for {queueName} is: {response.QueueUrl}"); } Actions 323 Amazon Simple Queue Service } Developer Guide catch (QueueDoesNotExistException ex) { Console.WriteLine(ex.Message); Console.WriteLine($"The queue {queueName} was not found."); } } } • For API details, see GetQueueUrl in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Get the URL for an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueName: An Amazon SQS queue name. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::getQueueUrl(const Aws::String &queueName, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::GetQueueUrlRequest request; request.SetQueueName(queueName); Actions 324 Amazon Simple Queue Service Developer Guide const Aws::SQS::Model::GetQueueUrlOutcome outcome = sqsClient.GetQueueUrl(request); if (outcome.IsSuccess()) { std::cout << "Queue " << queueName << " has url " << outcome.GetResult().GetQueueUrl() << std::endl; } else { std::cerr << "Error getting url for queue " << queueName << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see GetQueueUrl in AWS SDK for C++ API Reference. CLI AWS CLI To get a queue URL This example gets the specified queue's URL. Command: aws sqs get-queue-url --queue-name MyQueue Output: { "QueueUrl": "https://queue.amazonaws.com/80398EXAMPLE/MyQueue" } • For API details, see GetQueueUrl in AWS CLI Command Reference. Actions 325 Amazon Simple Queue Service Java SDK for Java 2.x Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. GetQueueUrlResponse getQueueUrlResponse = sqsClient .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()); return getQueueUrlResponse.queueUrl(); • For API details, see GetQueueUrl in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Get the URL for an Amazon SQS queue. import { GetQueueUrlCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_NAME = "test-queue"; export const main = async (queueName = SQS_QUEUE_NAME) => { const command = new GetQueueUrlCommand({ QueueName: queueName }); const response = await client.send(command); console.log(response); Actions 326 Amazon Simple Queue Service Developer Guide return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see GetQueueUrl in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Get the URL for an Amazon SQS queue. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set
|
sqs-dg-093
|
sqs-dg.pdf
| 93 |
SQS_QUEUE_NAME) => { const command = new GetQueueUrlCommand({ QueueName: queueName }); const response = await client.send(command); console.log(response); Actions 326 Amazon Simple Queue Service Developer Guide return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see GetQueueUrl in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Get the URL for an Amazon SQS queue. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create an SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { QueueName: "SQS_QUEUE_NAME", }; sqs.getQueueUrl(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.QueueUrl); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see GetQueueUrl in AWS SDK for JavaScript API Reference. Actions 327 Amazon Simple Queue Service PowerShell Tools for PowerShell Developer Guide Example 1: This example lists the URL of the queue with the specified name. Get-SQSQueueUrl -QueueName MyQueue Output: https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue • For API details, see GetQueueUrl in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. def get_queue(name): """ Gets an SQS queue by name. :param name: The name that was used to create the queue. :return: A Queue object. """ try: queue = sqs.get_queue_by_name(QueueName=name) logger.info("Got queue '%s' with URL=%s", name, queue.url) except ClientError as error: logger.exception("Couldn't get queue named %s.", name) raise error else: return queue Actions 328 Amazon Simple Queue Service Developer Guide • For API details, see GetQueueUrl in AWS SDK for Python (Boto3) API Reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. oo_result = lo_sqs->getqueueurl( iv_queuename = iv_queue_name ). " oo_result is returned for testing purposes. " MESSAGE 'Queue URL retrieved.' TYPE 'I'. CATCH /aws1/cx_sqsqueuedoesnotexist. MESSAGE 'The requested queue does not exist.' TYPE 'E'. ENDTRY. • For API details, see GetQueueUrl in AWS SDK for SAP ABAP API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use ListDeadLetterSourceQueues with a CLI The following code examples show how to use ListDeadLetterSourceQueues. CLI AWS CLI To list dead letter source queues Actions 329 Amazon Simple Queue Service Developer Guide This example lists the queues that are associated with the specified dead letter source queue. Command: aws sqs list-dead-letter-source-queues --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue Output: { "queueUrls": [ "https://queue.amazonaws.com/80398EXAMPLE/MyQueue", "https://queue.amazonaws.com/80398EXAMPLE/MyOtherQueue" ] } • For API details, see ListDeadLetterSourceQueues in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example lists the URLs of any queues that rely on the specified queue as their dead letter queue. Get-SQSDeadLetterSourceQueue -QueueUrl https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue Output: https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue • For API details, see ListDeadLetterSourceQueues in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 330 Amazon Simple Queue Service Developer Guide Use ListQueues with an AWS SDK or CLI The following code examples show how to use ListQueues. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! List the Amazon Simple Queue Service (Amazon SQS) queues within an AWS account. /*! \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::listQueues(const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::ListQueuesRequest listQueuesRequest; Aws::String nextToken; // Used for pagination. Aws::Vector<Aws::String> allQueueUrls; do { if (!nextToken.empty()) { listQueuesRequest.SetNextToken(nextToken); } const Aws::SQS::Model::ListQueuesOutcome outcome = sqsClient.ListQueues( listQueuesRequest); if (outcome.IsSuccess()) { Actions 331 Amazon Simple Queue Service Developer Guide const Aws::Vector<Aws::String> &queueUrls = outcome.GetResult().GetQueueUrls(); allQueueUrls.insert(allQueueUrls.end(), queueUrls.begin(), queueUrls.end()); nextToken = outcome.GetResult().GetNextToken(); } else { std::cerr << "Error listing queues: " << outcome.GetError().GetMessage() << std::endl; return false; } } while (!nextToken.empty()); std::cout << allQueueUrls.size() << " Amazon SQS queue(s) found." << std::endl; for (const auto &iter: allQueueUrls) { std::cout << " " << iter << std::endl; } return true; } • For API details, see ListQueues in AWS SDK for C++ API Reference. CLI AWS CLI To list queues This example lists all queues. Command: aws sqs list-queues Output: { Actions 332
|
sqs-dg-094
|
sqs-dg.pdf
| 94 |
{ Actions 331 Amazon Simple Queue Service Developer Guide const Aws::Vector<Aws::String> &queueUrls = outcome.GetResult().GetQueueUrls(); allQueueUrls.insert(allQueueUrls.end(), queueUrls.begin(), queueUrls.end()); nextToken = outcome.GetResult().GetNextToken(); } else { std::cerr << "Error listing queues: " << outcome.GetError().GetMessage() << std::endl; return false; } } while (!nextToken.empty()); std::cout << allQueueUrls.size() << " Amazon SQS queue(s) found." << std::endl; for (const auto &iter: allQueueUrls) { std::cout << " " << iter << std::endl; } return true; } • For API details, see ListQueues in AWS SDK for C++ API Reference. CLI AWS CLI To list queues This example lists all queues. Command: aws sqs list-queues Output: { Actions 332 Amazon Simple Queue Service "QueueUrls": [ Developer Guide "https://queue.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue", "https://queue.amazonaws.com/80398EXAMPLE/MyQueue", "https://queue.amazonaws.com/80398EXAMPLE/MyOtherQueue", "https://queue.amazonaws.com/80398EXAMPLE/TestQueue1", "https://queue.amazonaws.com/80398EXAMPLE/TestQueue2" ] } This example lists only queues that start with "My". Command: aws sqs list-queues --queue-name-prefix My Output: { "QueueUrls": [ "https://queue.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue", "https://queue.amazonaws.com/80398EXAMPLE/MyQueue", "https://queue.amazonaws.com/80398EXAMPLE/MyOtherQueue" ] } • For API details, see ListQueues in AWS CLI Command Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. package main import ( Actions 333 Amazon Simple Queue Service Developer Guide "context" "fmt" "log" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sqs" ) // main uses the AWS SDK for Go V2 to create an Amazon Simple Queue Service // (Amazon SQS) client and list the queues in your account. // This example uses the default settings specified in your shared credentials // and config files. func main() { ctx := context.Background() sdkConfig, err := config.LoadDefaultConfig(ctx) if err != nil { fmt.Println("Couldn't load default configuration. Have you set up your AWS account?") fmt.Println(err) return } sqsClient := sqs.NewFromConfig(sdkConfig) fmt.Println("Let's list the queues for your account.") var queueUrls []string paginator := sqs.NewListQueuesPaginator(sqsClient, &sqs.ListQueuesInput{}) for paginator.HasMorePages() { output, err := paginator.NextPage(ctx) if err != nil { log.Printf("Couldn't get queues. Here's why: %v\n", err) break } else { queueUrls = append(queueUrls, output.QueueUrls...) } } if len(queueUrls) == 0 { fmt.Println("You don't have any queues!") } else { for _, queueUrl := range queueUrls { fmt.Printf("\t%v\n", queueUrl) } } } Actions 334 Amazon Simple Queue Service Developer Guide • For API details, see ListQueues in AWS SDK for Go API Reference. 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. String prefix = "que"; try { ListQueuesRequest listQueuesRequest = ListQueuesRequest.builder().queueNamePrefix(prefix).build(); ListQueuesResponse listQueuesResponse = sqsClient.listQueues(listQueuesRequest); for (String url : listQueuesResponse.queueUrls()) { System.out.println(url); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } • For API details, see ListQueues in AWS SDK for Java 2.x API Reference. Actions 335 Amazon Simple Queue Service JavaScript SDK for JavaScript (v3) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. List your Amazon SQS queues. import { paginateListQueues, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); export const main = async () => { const paginatedListQueues = paginateListQueues({ client }, {}); /** @type {string[]} */ const urls = []; for await (const page of paginatedListQueues) { const nextUrls = page.QueueUrls?.filter((qurl) => !!qurl) || []; urls.push(...nextUrls); for (const url of urls) { console.log(url); } } return urls; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see ListQueues in AWS SDK for JavaScript API Reference. Actions 336 Amazon Simple Queue Service SDK for JavaScript (v2) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. List your Amazon SQS queues. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create an SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = {}; sqs.listQueues(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.QueueUrls); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see ListQueues in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 337 Amazon Simple Queue Service Developer Guide suspend fun listQueues() { println("\nList Queues") val prefix = "que" val listQueuesRequest = ListQueuesRequest { queueNamePrefix = prefix } SqsClient { region = "us-east-1" }.use { sqsClient -> val response = sqsClient.listQueues(listQueuesRequest) response.queueUrls?.forEach { url -> println(url) } } } • For API details, see ListQueues in AWS SDK for Kotlin API reference. PowerShell Tools for PowerShell Example 1: This example lists all queues. Get-SQSQueue Output: https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/AnotherQueue https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/DeadLetterQueue https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue Example 2: This example lists any queues that start with the specified name. Get-SQSQueue -QueueNamePrefix My
|
sqs-dg-095
|
sqs-dg.pdf
| 95 |
the AWS Code Examples Repository. Actions 337 Amazon Simple Queue Service Developer Guide suspend fun listQueues() { println("\nList Queues") val prefix = "que" val listQueuesRequest = ListQueuesRequest { queueNamePrefix = prefix } SqsClient { region = "us-east-1" }.use { sqsClient -> val response = sqsClient.listQueues(listQueuesRequest) response.queueUrls?.forEach { url -> println(url) } } } • For API details, see ListQueues in AWS SDK for Kotlin API reference. PowerShell Tools for PowerShell Example 1: This example lists all queues. Get-SQSQueue Output: https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/AnotherQueue https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/DeadLetterQueue https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue Example 2: This example lists any queues that start with the specified name. Get-SQSQueue -QueueNamePrefix My Output: Actions 338 Amazon Simple Queue Service Developer Guide https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyOtherQueue https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyDeadLetterQueue • For API details, see ListQueues in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. def get_queues(prefix=None): """ Gets a list of SQS queues. When a prefix is specified, only queues with names that start with the prefix are returned. :param prefix: The prefix used to restrict the list of returned queues. :return: A list of Queue objects. """ if prefix: queue_iter = sqs.queues.filter(QueueNamePrefix=prefix) else: queue_iter = sqs.queues.all() queues = list(queue_iter) if queues: logger.info("Got queues: %s", ", ".join([q.url for q in queues])) else: logger.warning("No queues found.") return queues • For API details, see ListQueues in AWS SDK for Python (Boto3) API Reference. Actions 339 Amazon Simple Queue Service Ruby SDK for Ruby Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'aws-sdk-sqs' require 'aws-sdk-sts' # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @example # list_queue_urls(Aws::SQS::Client.new(region: 'us-west-2')) def list_queue_urls(sqs_client) queues = sqs_client.list_queues queues.queue_urls.each do |url| puts url end rescue StandardError => e puts "Error listing queue URLs: #{e.message}" end # Lists the attributes of a queue in Amazon Simple Queue Service (Amazon SQS). # # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. # @example # list_queue_attributes( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' # ) def list_queue_attributes(sqs_client, queue_url) attributes = sqs_client.get_queue_attributes( queue_url: queue_url, attribute_names: ['All'] ) Actions 340 Amazon Simple Queue Service Developer Guide attributes.attributes.each do |key, value| puts "#{key}: #{value}" end rescue StandardError => e puts "Error getting queue attributes: #{e.message}" end # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me region = 'us-west-2' queue_name = 'my-queue' sqs_client = Aws::SQS::Client.new(region: region) puts 'Listing available queue URLs...' list_queue_urls(sqs_client) sts_client = Aws::STS::Client.new(region: region) # For example: # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' queue_url = "https://sqs.#{region}.amazonaws.com/ #{sts_client.get_caller_identity.account}/#{queue_name}" puts "\nGetting information about queue '#{queue_name}'..." list_queue_attributes(sqs_client, queue_url) end • For API details, see ListQueues in AWS SDK for Ruby API Reference. Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 341 Amazon Simple Queue Service Developer Guide Retrieve the first Amazon SQS queue listed in the Region. async fn find_first_queue(client: &Client) -> Result<String, Error> { let queues = client.list_queues().send().await?; let queue_urls = queues.queue_urls(); Ok(queue_urls .first() .expect("No queues in this account and Region. Create a queue to proceed.") .to_string()) } • For API details, see ListQueues in AWS SDK for Rust API reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. oo_result = lo_sqs->listqueues( ). " oo_result is returned for testing purposes. " MESSAGE 'Retrieved list of queues.' TYPE 'I'. ENDTRY. • For API details, see ListQueues in AWS SDK for SAP ABAP API reference. Actions 342 Amazon Simple Queue Service Swift SDK for Swift Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSQS let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) var queues: [String] = [] let outputPages = sqsClient.listQueuesPaginated( input: ListQueuesInput() ) // Each time a page of results arrives, process its contents. for try await output in outputPages { guard let urls = output.queueUrls else { print("No queues found.") return } // Iterate over the queue URLs listed on this page, adding them // to the `queues` array. for queueUrl in urls { queues.append(queueUrl) } } • For API details, see ListQueues in AWS SDK for Swift API reference. Actions 343 Amazon Simple Queue Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use PurgeQueue with a CLI The following code examples
|
sqs-dg-096
|
sqs-dg.pdf
| 96 |
let urls = output.queueUrls else { print("No queues found.") return } // Iterate over the queue URLs listed on this page, adding them // to the `queues` array. for queueUrl in urls { queues.append(queueUrl) } } • For API details, see ListQueues in AWS SDK for Swift API reference. Actions 343 Amazon Simple Queue Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use PurgeQueue with a CLI The following code examples show how to use PurgeQueue. CLI AWS CLI To purge a queue This example deletes all messages in the specified queue. Command: aws sqs purge-queue --queue-url https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/ MyNewQueue Output: None. • For API details, see PurgeQueue in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example deletes all messages from the specified queue. Clear-SQSQueue -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue • For API details, see PurgeQueue in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 344 Amazon Simple Queue Service Developer Guide Use ReceiveMessage with an AWS SDK or CLI The following code examples show how to use ReceiveMessage. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code examples: • Process S3 event notifications • Publish messages to queues • Send and receive batches of messages .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Receive messages from a queue by using its URL. /// <summary> /// Receive messages from a queue by its URL. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>The list of messages.</returns> public async Task<List<Message>> ReceiveMessagesByUrl(string queueUrl, int maxMessages) { // Setting WaitTimeSeconds to non-zero enables long polling. // For information about long polling, see // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/ SQSDeveloperGuide/sqs-short-and-long-polling.html var messageResponse = await _amazonSQSClient.ReceiveMessageAsync( new ReceiveMessageRequest() { QueueUrl = queueUrl, MaxNumberOfMessages = maxMessages, WaitTimeSeconds = 1 Actions 345 Amazon Simple Queue Service }); return messageResponse.Messages; } Developer Guide Receive a message from an Amazon SQS queue, and then delete the message. public static async Task Main() { // If the AWS Region you want to use is different from // the AWS Region defined for the default user, supply // the specify your AWS Region to the client constructor. var client = new AmazonSQSClient(); string queueName = "Example_Queue"; var queueUrl = await GetQueueUrl(client, queueName); Console.WriteLine($"The SQS queue's URL is {queueUrl}"); var response = await ReceiveAndDeleteMessage(client, queueUrl); Console.WriteLine($"Message: {response.Messages[0]}"); } /// <summary> /// Retrieve the queue URL for the queue named in the queueName /// property using the client object. /// </summary> /// <param name="client">The Amazon SQS client used to retrieve the /// queue URL.</param> /// <param name="queueName">A string representing name of the queue /// for which to retrieve the URL.</param> /// <returns>The URL of the queue.</returns> public static async Task<string> GetQueueUrl(IAmazonSQS client, string queueName) { var request = new GetQueueUrlRequest { QueueName = queueName, }; GetQueueUrlResponse response = await client.GetQueueUrlAsync(request); return response.QueueUrl; Actions 346 Amazon Simple Queue Service } Developer Guide /// <summary> /// Retrieves the message from the quque at the URL passed in the /// queueURL parameters using the client. /// </summary> /// <param name="client">The SQS client used to retrieve a message.</ param> /// <param name="queueUrl">The URL of the queue from which to retrieve /// a message.</param> /// <returns>The response from the call to ReceiveMessageAsync.</returns> public static async Task<ReceiveMessageResponse> ReceiveAndDeleteMessage(IAmazonSQS client, string queueUrl) { // Receive a single message from the queue. var receiveMessageRequest = new ReceiveMessageRequest { AttributeNames = { "SentTimestamp" }, MaxNumberOfMessages = 1, MessageAttributeNames = { "All" }, QueueUrl = queueUrl, VisibilityTimeout = 0, WaitTimeSeconds = 0, }; var receiveMessageResponse = await client.ReceiveMessageAsync(receiveMessageRequest); // Delete the received message from the queue. var deleteMessageRequest = new DeleteMessageRequest { QueueUrl = queueUrl, ReceiptHandle = receiveMessageResponse.Messages[0].ReceiptHandle, }; await client.DeleteMessageAsync(deleteMessageRequest); return receiveMessageResponse; } } • For API details, see ReceiveMessage in AWS SDK for .NET API Reference. Actions 347 Amazon Simple Queue Service C++ SDK for C++ Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Receive a message from an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::receiveMessage(const Aws::String &queueUrl, const Aws::Client::ClientConfiguration &clientConfiguration) {
|
sqs-dg-097
|
sqs-dg.pdf
| 97 |
details, see ReceiveMessage in AWS SDK for .NET API Reference. Actions 347 Amazon Simple Queue Service C++ SDK for C++ Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Receive a message from an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::receiveMessage(const Aws::String &queueUrl, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::ReceiveMessageRequest request; request.SetQueueUrl(queueUrl); request.SetMaxNumberOfMessages(1); const Aws::SQS::Model::ReceiveMessageOutcome outcome = sqsClient.ReceiveMessage( request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::SQS::Model::Message> &messages = outcome.GetResult().GetMessages(); if (!messages.empty()) { const Aws::SQS::Model::Message &message = messages[0]; std::cout << "Received message:" << std::endl; std::cout << " MessageId: " << message.GetMessageId() << std::endl; std::cout << " ReceiptHandle: " << message.GetReceiptHandle() << std::endl; Actions 348 Amazon Simple Queue Service Developer Guide std::cout << " Body: " << message.GetBody() << std::endl << std::endl; } else { std::cout << "No messages received from queue " << queueUrl << std::endl; } } else { std::cerr << "Error receiving message from queue " << queueUrl << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see ReceiveMessage in AWS SDK for C++ API Reference. CLI AWS CLI To receive a message This example receives up to 10 available messages, returning all available attributes. Command: aws sqs receive-message --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --attribute-names All --message- attribute-names All --max-number-of-messages 10 Output: { "Messages": [ { "Body": "My first message.", "ReceiptHandle": "AQEBzbVv...fqNzFw==", "MD5OfBody": "1000f835...a35411fa", "MD5OfMessageAttributes": "9424c491...26bc3ae7", Actions 349 Amazon Simple Queue Service Developer Guide "MessageId": "d6790f8d-d575-4f01-bc51-40122EXAMPLE", "Attributes": { "ApproximateFirstReceiveTimestamp": "1442428276921", "SenderId": "AIDAIAZKMSNQ7TEXAMPLE", "ApproximateReceiveCount": "5", "SentTimestamp": "1442428276921" }, "MessageAttributes": { "PostalCode": { "DataType": "String", "StringValue": "ABC123" }, "City": { "DataType": "String", "StringValue": "Any City" } } } ] } This example receives the next available message, returning only the SenderId and SentTimestamp attributes as well as the PostalCode message attribute. Command: aws sqs receive-message --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --attribute- names SenderId SentTimestamp --message-attribute-names PostalCode Output: { "Messages": [ { "Body": "My first message.", "ReceiptHandle": "AQEB6nR4...HzlvZQ==", "MD5OfBody": "1000f835...a35411fa", "MD5OfMessageAttributes": "b8e89563...e088e74f", "MessageId": "d6790f8d-d575-4f01-bc51-40122EXAMPLE", "Attributes": { "SenderId": "AIDAIAZKMSNQ7TEXAMPLE", "SentTimestamp": "1442428276921" Actions 350 Developer Guide Amazon Simple Queue Service }, "MessageAttributes": { "PostalCode": { "DataType": "String", "StringValue": "ABC123" } } } ] } • For API details, see ReceiveMessage in AWS CLI Command Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import ( "context" "encoding/json" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" ) // SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions // used in the examples. type SqsActions struct { SqsClient *sqs.Client } Actions 351 Amazon Simple Queue Service Developer Guide // GetMessages uses the ReceiveMessage action to get messages from an Amazon SQS queue. func (actor SqsActions) GetMessages(ctx context.Context, queueUrl string, maxMessages int32, waitTime int32) ([]types.Message, error) { var messages []types.Message result, err := actor.SqsClient.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{ QueueUrl: aws.String(queueUrl), MaxNumberOfMessages: maxMessages, WaitTimeSeconds: waitTime, }) if err != nil { log.Printf("Couldn't get messages from queue %v. Here's why: %v\n", queueUrl, err) } else { messages = result.Messages } return messages, err } • For API details, see ReceiveMessage in AWS SDK for Go API Reference. 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. try { ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder() .queueUrl(queueUrl) .maxNumberOfMessages(5) .build(); return sqsClient.receiveMessage(receiveMessageRequest).messages(); Actions 352 Amazon Simple Queue Service Developer Guide } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; • For API details, see ReceiveMessage in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Receive a message from an Amazon SQS queue. import { ReceiveMessageCommand, DeleteMessageCommand, SQSClient, DeleteMessageBatchCommand, } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; const receiveMessage = (queueUrl) => client.send( new ReceiveMessageCommand({ AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 10, MessageAttributeNames: ["All"], QueueUrl: queueUrl, WaitTimeSeconds: 20, VisibilityTimeout: 20, }), ); Actions 353 Amazon Simple Queue Service Developer Guide export const main = async (queueUrl = SQS_QUEUE_URL) => { const { Messages } = await receiveMessage(queueUrl); if (!Messages) { return; } if (Messages.length === 1) { console.log(Messages[0].Body); await client.send( new DeleteMessageCommand({ QueueUrl: queueUrl, ReceiptHandle: Messages[0].ReceiptHandle, }), ); } else { await client.send( new DeleteMessageBatchCommand({ QueueUrl: queueUrl, Entries: Messages.map((message) => ({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle, })), }), ); } }; Receive a message from an Amazon SQS queue using long-poll support. import { ReceiveMessageCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue-url"; export const
|
sqs-dg-098
|
sqs-dg.pdf
| 98 |
20, }), ); Actions 353 Amazon Simple Queue Service Developer Guide export const main = async (queueUrl = SQS_QUEUE_URL) => { const { Messages } = await receiveMessage(queueUrl); if (!Messages) { return; } if (Messages.length === 1) { console.log(Messages[0].Body); await client.send( new DeleteMessageCommand({ QueueUrl: queueUrl, ReceiptHandle: Messages[0].ReceiptHandle, }), ); } else { await client.send( new DeleteMessageBatchCommand({ QueueUrl: queueUrl, Entries: Messages.map((message) => ({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle, })), }), ); } }; Receive a message from an Amazon SQS queue using long-poll support. import { ReceiveMessageCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue-url"; export const main = async (queueUrl = SQS_QUEUE_URL) => { const command = new ReceiveMessageCommand({ AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 1, MessageAttributeNames: ["All"], QueueUrl: queueUrl, Actions 354 Amazon Simple Queue Service Developer Guide // The duration (in seconds) for which the call waits for a message // to arrive in the queue before returning. If a message is available, // the call returns sooner than WaitTimeSeconds. If no messages are // available and the wait time expires, the call returns successfully // with an empty list of messages. // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/ API_ReceiveMessage.html#API_ReceiveMessage_RequestSyntax WaitTimeSeconds: 20, }); const response = await client.send(command); console.log(response); return response; }; • For API details, see ReceiveMessage in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Receive a message from an Amazon SQS queue using long-poll support. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create the SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var queueURL = "SQS_QUEUE_URL"; var params = { AttributeNames: ["SentTimestamp"], MaxNumberOfMessages: 1, MessageAttributeNames: ["All"], QueueUrl: queueURL, Actions 355 Amazon Simple Queue Service Developer Guide WaitTimeSeconds: 20, }; sqs.receiveMessage(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see ReceiveMessage in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun receiveMessages(queueUrlVal: String?) { println("Retrieving messages from $queueUrlVal") val receiveMessageRequest = ReceiveMessageRequest { queueUrl = queueUrlVal maxNumberOfMessages = 5 } SqsClient { region = "us-east-1" }.use { sqsClient -> val response = sqsClient.receiveMessage(receiveMessageRequest) response.messages?.forEach { message -> println(message.body) } } } Actions 356 Amazon Simple Queue Service Developer Guide • For API details, see ReceiveMessage in AWS SDK for Kotlin API reference. PowerShell Tools for PowerShell Example 1: This example lists information for up to the next 10 messages to be received for the specified queue. The information will contain values for the specified message attributes, if they exist. Receive-SQSMessage -AttributeName SenderId, SentTimestamp -MessageAttributeName StudentName, StudentGrade -MessageCount 10 -QueueUrl https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue Output: Attributes : {[SenderId, AIDAIAZKMSNQ7TEXAMPLE], [SentTimestamp, 1451495923744]} Body : Information about John Doe's grade. MD5OfBody : ea572796e3c231f974fe75d89EXAMPLE MD5OfMessageAttributes : 48c1ee811f0fe7c4e88fbe0f5EXAMPLE MessageAttributes : {[StudentGrade, Amazon.SQS.Model.MessageAttributeValue], [StudentName, Amazon.SQS.Model.MessageAttributeValue]} MessageId : 53828c4b-631b-469b-8833-c093cEXAMPLE ReceiptHandle : AQEBpfGp...20Q5cg== • For API details, see ReceiveMessage in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 357 Amazon Simple Queue Service Developer Guide def receive_messages(queue, max_number, wait_time): """ Receive a batch of messages in a single request from an SQS queue. :param queue: The queue from which to receive messages. :param max_number: The maximum number of messages to receive. The actual number of messages received might be less. :param wait_time: 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. """ try: messages = queue.receive_messages( MessageAttributeNames=["All"], MaxNumberOfMessages=max_number, WaitTimeSeconds=wait_time, ) for msg in messages: logger.info("Received message: %s: %s", msg.message_id, msg.body) except ClientError as error: logger.exception("Couldn't receive messages from queue: %s", queue) raise error else: return messages • For API details, see ReceiveMessage in AWS SDK for Python (Boto3) API Reference. Actions 358 Amazon Simple Queue Service Ruby SDK for Ruby Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'aws-sdk-sqs' require 'aws-sdk-sts' # Receives messages in a queue in Amazon Simple Queue Service (Amazon SQS). # # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. # @param max_number_of_messages [Integer] The maximum number of messages # to
|
sqs-dg-099
|
sqs-dg.pdf
| 99 |
error else: return messages • For API details, see ReceiveMessage in AWS SDK for Python (Boto3) API Reference. Actions 358 Amazon Simple Queue Service Ruby SDK for Ruby Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'aws-sdk-sqs' require 'aws-sdk-sts' # Receives messages in a queue in Amazon Simple Queue Service (Amazon SQS). # # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. # @param max_number_of_messages [Integer] The maximum number of messages # to receive. This number must be 10 or less. The default is 10. # @example # receive_messages( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue', # 10 # ) def receive_messages(sqs_client, queue_url, max_number_of_messages = 10) if max_number_of_messages > 10 puts 'Maximum number of messages to receive must be 10 or less. ' \ 'Stopping program.' return end response = sqs_client.receive_message( queue_url: queue_url, max_number_of_messages: max_number_of_messages ) if response.messages.count.zero? puts 'No messages to receive, or all messages have already ' \ 'been previously received.' return Actions 359 Amazon Simple Queue Service end Developer Guide response.messages.each do |message| puts '-' * 20 puts "Message body: #{message.body}" puts "Message ID: #{message.message_id}" end rescue StandardError => e puts "Error receiving messages: #{e.message}" end # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me region = 'us-west-2' queue_name = 'my-queue' max_number_of_messages = 10 sts_client = Aws::STS::Client.new(region: region) # For example: # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' queue_url = "https://sqs.#{region}.amazonaws.com/ #{sts_client.get_caller_identity.account}/#{queue_name}" sqs_client = Aws::SQS::Client.new(region: region) puts "Receiving messages from queue '#{queue_name}'..." receive_messages(sqs_client, queue_url, max_number_of_messages) end # Example usage: run_me if $PROGRAM_NAME == __FILE__ • For API details, see ReceiveMessage in AWS SDK for Ruby API Reference. Actions 360 Amazon Simple Queue Service Rust SDK for Rust Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. async fn receive(client: &Client, queue_url: &String) -> Result<(), Error> { let rcv_message_output = client.receive_message().queue_url(queue_url).send().await?; println!("Messages from queue with url: {}", queue_url); for message in rcv_message_output.messages.unwrap_or_default() { println!("Got the message: {:#?}", message); } Ok(()) } • For API details, see ReceiveMessage in AWS SDK for Rust API reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Receive a message from an Amazon SQS queue. TRY. Actions 361 Amazon Simple Queue Service Developer Guide oo_result = lo_sqs->receivemessage( iv_queueurl = iv_queue_url ). " oo_result is returned for testing purposes. " DATA(lt_messages) = oo_result->get_messages( ). MESSAGE 'Message received from SQS queue.' TYPE 'I'. CATCH /aws1/cx_sqsoverlimit. MESSAGE 'Maximum number of in-flight messages reached.' TYPE 'E'. ENDTRY. Receive a message from an Amazon SQS queue using long-poll support. TRY. oo_result = lo_sqs->receivemessage( " oo_result is returned for testing purposes. " iv_queueurl = iv_queue_url iv_waittimeseconds = iv_wait_time ). " Time in seconds for long polling, such as how long the call waits for a message to arrive in the queue before returning. " ). DATA(lt_messages) = oo_result->get_messages( ). MESSAGE 'Message received from SQS queue.' TYPE 'I'. CATCH /aws1/cx_sqsoverlimit. MESSAGE 'Maximum number of in-flight messages reached.' TYPE 'E'. ENDTRY. • For API details, see ReceiveMessage in AWS SDK for SAP ABAP API reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSQS let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) Actions 362 Amazon Simple Queue Service Developer Guide let output = try await sqsClient.receiveMessage( input: ReceiveMessageInput( maxNumberOfMessages: maxMessages, queueUrl: url ) ) guard let messages = output.messages else { print("No messages received.") return } for message in messages { print("Message ID: \(message.messageId ?? "<unknown>")") print("Receipt handle: \(message.receiptHandle ?? "<unknown>")") print(message.body ?? "<body missing>") print("---") } • For API details, see ReceiveMessage in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use RemovePermission with a CLI The following code examples show how to use RemovePermission. CLI AWS CLI To remove a permission This example removes the permission with the specified label from the specified queue. Command: Actions 363 Amazon Simple Queue Service Developer Guide aws sqs remove-permission --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --label SendMessagesFromMyQueue Output: None. • For API details, see RemovePermission in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example removes the permission settings with the specified label from the specified queue. Remove-SQSPermission -Label SendMessagesFromMyQueue -QueueUrl https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue • For API details, see RemovePermission in AWS Tools for PowerShell Cmdlet Reference. For a complete list
|
sqs-dg-100
|
sqs-dg.pdf
| 100 |
code examples show how to use RemovePermission. CLI AWS CLI To remove a permission This example removes the permission with the specified label from the specified queue. Command: Actions 363 Amazon Simple Queue Service Developer Guide aws sqs remove-permission --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --label SendMessagesFromMyQueue Output: None. • For API details, see RemovePermission in AWS CLI Command Reference. PowerShell Tools for PowerShell Example 1: This example removes the permission settings with the specified label from the specified queue. Remove-SQSPermission -Label SendMessagesFromMyQueue -QueueUrl https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue • For API details, see RemovePermission in AWS Tools for PowerShell Cmdlet Reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use SendMessage with an AWS SDK or CLI The following code examples show how to use SendMessage. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Actions 364 Amazon Simple Queue Service Developer Guide Create an Amazon SQS queue and send a message to it. using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon; using Amazon.SQS; using Amazon.SQS.Model; public class CreateSendExample { // Specify your AWS Region (an example Region is shown). private static readonly string QueueName = "Example_Queue"; private static readonly RegionEndpoint ServiceRegion = RegionEndpoint.USWest2; private static IAmazonSQS client; public static async Task Main() { client = new AmazonSQSClient(ServiceRegion); var createQueueResponse = await CreateQueue(client, QueueName); string queueUrl = createQueueResponse.QueueUrl; Dictionary<string, MessageAttributeValue> messageAttributes = new Dictionary<string, MessageAttributeValue> { { "Title", new MessageAttributeValue { DataType = "String", StringValue = "The Whistler" } }, { "Author", new MessageAttributeValue { DataType = "String", StringValue = "John Grisham" } }, { "WeeksOn", new MessageAttributeValue { DataType = "Number", StringValue = "6" } }, }; string messageBody = "Information about current NY Times fiction bestseller for week of 12/11/2016."; var sendMsgResponse = await SendMessage(client, queueUrl, messageBody, messageAttributes); } /// <summary> /// Creates a new Amazon SQS queue using the queue name passed to it Actions 365 Amazon Simple Queue Service Developer Guide /// in queueName. /// </summary> /// <param name="client">An SQS client object used to send the message.</ param> /// <param name="queueName">A string representing the name of the queue /// to create.</param> /// <returns>A CreateQueueResponse that contains information about the /// newly created queue.</returns> public static async Task<CreateQueueResponse> CreateQueue(IAmazonSQS client, string queueName) { var request = new CreateQueueRequest { QueueName = queueName, Attributes = new Dictionary<string, string> { { "DelaySeconds", "60" }, { "MessageRetentionPeriod", "86400" }, }, }; var response = await client.CreateQueueAsync(request); Console.WriteLine($"Created a queue with URL : {response.QueueUrl}"); return response; } /// <summary> /// Sends a message to an SQS queue. /// </summary> /// <param name="client">An SQS client object used to send the message.</ param> /// <param name="queueUrl">The URL of the queue to which to send the /// message.</param> /// <param name="messageBody">A string representing the body of the /// message to be sent to the queue.</param> /// <param name="messageAttributes">Attributes for the message to be /// sent to the queue.</param> /// <returns>A SendMessageResponse object that contains information /// about the message that was sent.</returns> public static async Task<SendMessageResponse> SendMessage( IAmazonSQS client, string queueUrl, string messageBody, Actions 366 Amazon Simple Queue Service Developer Guide Dictionary<string, MessageAttributeValue> messageAttributes) { var sendMessageRequest = new SendMessageRequest { DelaySeconds = 10, MessageAttributes = messageAttributes, MessageBody = messageBody, QueueUrl = queueUrl, }; var response = await client.SendMessageAsync(sendMessageRequest); Console.WriteLine($"Sent a message with id : {response.MessageId}"); return response; } } • For API details, see SendMessage in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Send a message to an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. \param messageBody: A message body. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ Actions 367 Amazon Simple Queue Service Developer Guide bool AwsDoc::SQS::sendMessage(const Aws::String &queueUrl, const Aws::String &messageBody, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::SendMessageRequest request; request.SetQueueUrl(queueUrl); request.SetMessageBody(messageBody); const Aws::SQS::Model::SendMessageOutcome outcome = sqsClient.SendMessage(request); if (outcome.IsSuccess()) { std::cout << "Successfully sent message to " << queueUrl << std::endl; } else { std::cerr << "Error sending message to " << queueUrl << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see SendMessage in AWS SDK for C++ API Reference. CLI AWS CLI To send a message This example sends a message with the specified message body, delay period, and message attributes, to the specified queue. Command: aws sqs send-message --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --message-body "Information about the largest city in Any Region." --delay-seconds
|
sqs-dg-101
|
sqs-dg.pdf
| 101 |
request.SetQueueUrl(queueUrl); request.SetMessageBody(messageBody); const Aws::SQS::Model::SendMessageOutcome outcome = sqsClient.SendMessage(request); if (outcome.IsSuccess()) { std::cout << "Successfully sent message to " << queueUrl << std::endl; } else { std::cerr << "Error sending message to " << queueUrl << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see SendMessage in AWS SDK for C++ API Reference. CLI AWS CLI To send a message This example sends a message with the specified message body, delay period, and message attributes, to the specified queue. Command: aws sqs send-message --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --message-body "Information about the largest city in Any Region." --delay-seconds 10 --message-attributes file:// send-message.json Actions 368 Amazon Simple Queue Service Developer Guide Input file (send-message.json): { "City": { "DataType": "String", "StringValue": "Any City" }, "Greeting": { "DataType": "Binary", "BinaryValue": "Hello, World!" }, "Population": { "DataType": "Number", "StringValue": "1250800" } } Output: { "MD5OfMessageBody": "51b0a325...39163aa0", "MD5OfMessageAttributes": "00484c68...59e48f06", "MessageId": "da68f62c-0c07-4bee-bf5f-7e856EXAMPLE" } • For API details, see SendMessage in AWS CLI Command Reference. 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. Two examples of the SendMessage operation follow: • Send a message with a body and a delay • Send a message with a body and message attributes Actions 369 Amazon Simple Queue Service Developer Guide Send a message with a body and a delay. import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sqs.SqsClient; import software.amazon.awssdk.services.sqs.model.CreateQueueRequest; import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest; import software.amazon.awssdk.services.sqs.model.SendMessageRequest; import software.amazon.awssdk.services.sqs.model.SqsException; /** * 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 */ public class SendMessages { public static void main(String[] args) { final String usage = """ Usage: <queueName> <message> Where: queueName - The name of the queue. message - The message to send. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String queueName = args[0]; String message = args[1]; SqsClient sqsClient = SqsClient.builder() .region(Region.US_WEST_2) .build(); sendMessage(sqsClient, queueName, message); sqsClient.close(); } Actions 370 Amazon Simple Queue Service Developer Guide public static void sendMessage(SqsClient sqsClient, String queueName, String message) { try { CreateQueueRequest request = CreateQueueRequest.builder() .queueName(queueName) .build(); sqsClient.createQueue(request); GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder() .queueName(queueName) .build(); String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl(); SendMessageRequest sendMsgRequest = SendMessageRequest.builder() .queueUrl(queueUrl) .messageBody(message) .delaySeconds(5) .build(); sqsClient.sendMessage(sendMsgRequest); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } } Send a message with a body and message attributes. /** * <p>This method demonstrates how to add message attributes to a message. * Each attribute must specify a name, value, and data type. You use a Java Map to supply the attributes. The map's * key is the attribute name, and you specify the map's entry value using a builder that includes the attribute * value and data type.</p> * * <p>The data type must start with one of "String", "Number" or "Binary". You can optionally * define a custom extension by using a "." and your extension.</p> * Actions 371 Amazon Simple Queue Service Developer Guide * <p>The SQS Developer Guide provides more information on @see <a * href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/ SQSDeveloperGuide/sqs-message-metadata.html#sqs-message-attributes">message * attributes</a>.</p> * * @param thumbailPath Filesystem path of the image. * @param queueUrl URL of the SQS queue. */ static void sendMessageWithAttributes(Path thumbailPath, String queueUrl) { Map<String, MessageAttributeValue> messageAttributeMap; try { messageAttributeMap = Map.of( "Name", MessageAttributeValue.builder() .stringValue("Jane Doe") .dataType("String").build(), "Age", MessageAttributeValue.builder() .stringValue("42") .dataType("Number.int").build(), "Image", MessageAttributeValue.builder() .binaryValue(SdkBytes.fromByteArray(Files.readAllBytes(thumbailPath))) .dataType("Binary.jpg").build() ); } catch (IOException e) { LOGGER.error("An I/O exception occurred reading thumbnail image: {}", e.getMessage(), e); throw new RuntimeException(e); } SendMessageRequest request = SendMessageRequest.builder() .queueUrl(queueUrl) .messageBody("Hello SQS") .messageAttributes(messageAttributeMap) .build(); try { SendMessageResponse sendMessageResponse = SQS_CLIENT.sendMessage(request); LOGGER.info("Message ID: {}", sendMessageResponse.messageId()); } catch (SqsException e) { LOGGER.error("Exception occurred sending message: {}", e.getMessage(), e); throw new RuntimeException(e); } } Actions 372 Amazon Simple Queue Service Developer Guide • For API details, see SendMessage in AWS SDK for Java 2.x API Reference. JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Send a message to an Amazon SQS queue. import { SendMessageCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; export const main = async (sqsQueueUrl = SQS_QUEUE_URL) => { const command = new SendMessageCommand({ QueueUrl: sqsQueueUrl, DelaySeconds: 10, MessageAttributes: { Title: { DataType: "String", StringValue: "The Whistler", }, Author: { DataType: "String", StringValue: "John Grisham", }, WeeksOn: { DataType: "Number", StringValue: "6", }, }, MessageBody: "Information about current NY Times fiction bestseller for week of 12/11/2016.", Actions 373 Amazon Simple Queue Service }); Developer Guide const response = await client.send(command); console.log(response); return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see SendMessage in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more
|
sqs-dg-102
|
sqs-dg.pdf
| 102 |
= SQS_QUEUE_URL) => { const command = new SendMessageCommand({ QueueUrl: sqsQueueUrl, DelaySeconds: 10, MessageAttributes: { Title: { DataType: "String", StringValue: "The Whistler", }, Author: { DataType: "String", StringValue: "John Grisham", }, WeeksOn: { DataType: "Number", StringValue: "6", }, }, MessageBody: "Information about current NY Times fiction bestseller for week of 12/11/2016.", Actions 373 Amazon Simple Queue Service }); Developer Guide const response = await client.send(command); console.log(response); return response; }; • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see SendMessage in AWS SDK for JavaScript API Reference. SDK for JavaScript (v2) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Send a message to an Amazon SQS queue. // Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set the region AWS.config.update({ region: "REGION" }); // Create an SQS service object var sqs = new AWS.SQS({ apiVersion: "2012-11-05" }); var params = { // Remove DelaySeconds parameter and value for FIFO queues DelaySeconds: 10, MessageAttributes: { Title: { DataType: "String", StringValue: "The Whistler", }, Author: { DataType: "String", StringValue: "John Grisham", }, WeeksOn: { DataType: "Number", Actions 374 Amazon Simple Queue Service Developer Guide StringValue: "6", }, }, MessageBody: "Information about current NY Times fiction bestseller for week of 12/11/2016.", // MessageDeduplicationId: "TheWhistler", // Required for FIFO queues // MessageGroupId: "Group1", // Required for FIFO queues QueueUrl: "SQS_QUEUE_URL", }; sqs.sendMessage(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data.MessageId); } }); • For more information, see AWS SDK for JavaScript Developer Guide. • For API details, see SendMessage in AWS SDK for JavaScript API Reference. Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. suspend fun sendMessages( queueUrlVal: String, message: String, ) { println("Sending multiple messages") println("\nSend message") val sendRequest = SendMessageRequest { Actions 375 Amazon Simple Queue Service Developer Guide queueUrl = queueUrlVal messageBody = message delaySeconds = 10 } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.sendMessage(sendRequest) println("A single message was successfully sent.") } } suspend fun sendBatchMessages(queueUrlVal: String?) { println("Sending multiple messages") val msg1 = SendMessageBatchRequestEntry { id = "id1" messageBody = "Hello from msg 1" } val msg2 = SendMessageBatchRequestEntry { id = "id2" messageBody = "Hello from msg 2" } val sendMessageBatchRequest = SendMessageBatchRequest { queueUrl = queueUrlVal entries = listOf(msg1, msg2) } SqsClient { region = "us-east-1" }.use { sqsClient -> sqsClient.sendMessageBatch(sendMessageBatchRequest) println("Batch message were successfully sent.") } } • For API details, see SendMessage in AWS SDK for Kotlin API reference. Actions 376 Amazon Simple Queue Service PowerShell Tools for PowerShell Developer Guide Example 1: This example sends a message with the specified attributes and message body to the specified queue with message delivery delayed for 10 seconds. $cityAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $cityAttributeValue.DataType = "String" $cityAttributeValue.StringValue = "AnyCity" $populationAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $populationAttributeValue.DataType = "Number" $populationAttributeValue.StringValue = "1250800" $messageAttributes = New-Object System.Collections.Hashtable $messageAttributes.Add("City", $cityAttributeValue) $messageAttributes.Add("Population", $populationAttributeValue) Send-SQSMessage -DelayInSeconds 10 -MessageAttributes $messageAttributes - MessageBody "Information about the largest city in Any Region." -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue Output: MD5OfMessageAttributes MD5OfMessageBody MessageId ---------------------- ---------------- --------- 1d3e51347bc042efbdf6dda31EXAMPLE 51b0a3256d59467f973009b73EXAMPLE c35fed8f- c739-4d0c-818b-1820eEXAMPLE • For API details, see SendMessage in AWS Tools for PowerShell Cmdlet Reference. Actions 377 Amazon Simple Queue Service Python SDK for Python (Boto3) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. def send_message(queue, message_body, message_attributes=None): """ Send a message to an Amazon SQS queue. :param queue: The queue that receives the message. :param message_body: The body text of the message. :param message_attributes: Custom attributes of the message. These are key- value pairs that can be whatever you want. :return: The response from SQS that contains the assigned message ID. """ if not message_attributes: message_attributes = {} try: response = queue.send_message( MessageBody=message_body, MessageAttributes=message_attributes ) except ClientError as error: logger.exception("Send message failed: %s", message_body) raise error else: return response • For API details, see SendMessage in AWS SDK for Python (Boto3) API Reference. Actions 378 Amazon Simple Queue Service Ruby SDK for Ruby Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'aws-sdk-sqs' require 'aws-sdk-sts' # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. # @param message_body [String] The contents of the message to be sent. # @return [Boolean] true if the message was sent; otherwise, false. # @example # exit 1 unless message_sent?( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue', # 'This is my message.' # ) def message_sent?(sqs_client, queue_url, message_body) sqs_client.send_message( queue_url: queue_url, message_body: message_body ) true rescue StandardError =>
|
sqs-dg-103
|
sqs-dg.pdf
| 103 |
There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'aws-sdk-sqs' require 'aws-sdk-sts' # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. # @param message_body [String] The contents of the message to be sent. # @return [Boolean] true if the message was sent; otherwise, false. # @example # exit 1 unless message_sent?( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue', # 'This is my message.' # ) def message_sent?(sqs_client, queue_url, message_body) sqs_client.send_message( queue_url: queue_url, message_body: message_body ) true rescue StandardError => e puts "Error sending message: #{e.message}" false end # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me region = 'us-west-2' queue_name = 'my-queue' message_body = 'This is my message.' Actions 379 Amazon Simple Queue Service Developer Guide sts_client = Aws::STS::Client.new(region: region) # For example: # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' queue_url = "https://sqs.#{region}.amazonaws.com/ #{sts_client.get_caller_identity.account}/#{queue_name}" sqs_client = Aws::SQS::Client.new(region: region) puts "Sending a message to the queue named '#{queue_name}'..." if message_sent?(sqs_client, queue_url, message_body) puts 'Message sent.' else puts 'Message not sent.' end end # Example usage: run_me if $PROGRAM_NAME == __FILE__ • For API details, see SendMessage in AWS SDK for Ruby API Reference. Rust SDK for Rust Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. async fn send(client: &Client, queue_url: &String, message: &SQSMessage) -> Result<(), Error> { println!("Sending message to queue with URL: {}", queue_url); let rsp = client .send_message() .queue_url(queue_url) .message_body(&message.body) Actions 380 Amazon Simple Queue Service Developer Guide // If the queue is FIFO, you need to set .message_deduplication_id // and message_group_id or configure the queue for ContentBasedDeduplication. .send() .await?; println!("Send message to the queue: {:#?}", rsp); Ok(()) } • For API details, see SendMessage in AWS SDK for Rust API reference. SAP ABAP SDK for SAP ABAP Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. TRY. oo_result = lo_sqs->sendmessage( " oo_result is returned for testing purposes. " iv_queueurl = iv_queue_url iv_messagebody = iv_message ). MESSAGE 'Message sent to SQS queue.' TYPE 'I'. CATCH /aws1/cx_sqsinvalidmsgconts. MESSAGE 'Message contains non-valid characters.' TYPE 'E'. CATCH /aws1/cx_sqsunsupportedop. MESSAGE 'Operation not supported.' TYPE 'E'. ENDTRY. • For API details, see SendMessage in AWS SDK for SAP ABAP API reference. Actions 381 Amazon Simple Queue Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use SendMessageBatch with an AWS SDK or CLI The following code examples show how to use SendMessageBatch. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Send and receive batches of messages CLI AWS CLI To send multiple messages as a batch This example sends 2 messages with the specified message bodies, delay periods, and message attributes, to the specified queue. Command: aws sqs send-message-batch --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyQueue --entries file://send-message- batch.json Input file (send-message-batch.json): [ { "Id": "FuelReport-0001-2015-09-16T140731Z", "MessageBody": "Fuel report for account 0001 on 2015-09-16 at 02:07:31 PM.", "DelaySeconds": 10, "MessageAttributes": { "SellerName": { "DataType": "String", "StringValue": "Example Store" }, "City": { Actions 382 Amazon Simple Queue Service Developer Guide "DataType": "String", "StringValue": "Any City" }, "Region": { "DataType": "String", "StringValue": "WA" }, "PostalCode": { "DataType": "String", "StringValue": "99065" }, "PricePerGallon": { "DataType": "Number", "StringValue": "1.99" } } }, { "Id": "FuelReport-0002-2015-09-16T140930Z", "MessageBody": "Fuel report for account 0002 on 2015-09-16 at 02:09:30 PM.", "DelaySeconds": 10, "MessageAttributes": { "SellerName": { "DataType": "String", "StringValue": "Example Fuels" }, "City": { "DataType": "String", "StringValue": "North Town" }, "Region": { "DataType": "String", "StringValue": "WA" }, "PostalCode": { "DataType": "String", "StringValue": "99123" }, "PricePerGallon": { "DataType": "Number", "StringValue": "1.87" } } Actions 383 Amazon Simple Queue Service Developer Guide } ] Output: { "Successful": [ { "MD5OfMessageBody": "203c4a38...7943237e", "MD5OfMessageAttributes": "10809b55...baf283ef", "Id": "FuelReport-0001-2015-09-16T140731Z", "MessageId": "d175070c-d6b8-4101-861d-adeb3EXAMPLE" }, { "MD5OfMessageBody": "2cf0159a...c1980595", "MD5OfMessageAttributes": "55623928...ae354a25", "Id": "FuelReport-0002-2015-09-16T140930Z", "MessageId": "f9b7d55d-0570-413e-b9c5-a9264EXAMPLE" } ] } • For API details, see SendMessageBatch in AWS CLI Command Reference. 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. SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(SendMessageBatchRequestEntry.builder().id("id1").messageBody("Hello from msg 1").build(), Actions 384 Amazon Simple Queue Service Developer Guide SendMessageBatchRequestEntry.builder().id("id2").messageBody("msg 2").delaySeconds(10) .build()) .build(); sqsClient.sendMessageBatch(sendMessageBatchRequest); • For API details, see SendMessageBatch in AWS SDK for Java 2.x API Reference. PowerShell Tools for PowerShell Example 1: This example sends 2 messages with the specified attributes and message bodies to the specified queue. Delivery is delayed for 15 seconds for the first message
|
sqs-dg-104
|
sqs-dg.pdf
| 104 |
AWS CLI Command Reference. 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. SendMessageBatchRequest sendMessageBatchRequest = SendMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(SendMessageBatchRequestEntry.builder().id("id1").messageBody("Hello from msg 1").build(), Actions 384 Amazon Simple Queue Service Developer Guide SendMessageBatchRequestEntry.builder().id("id2").messageBody("msg 2").delaySeconds(10) .build()) .build(); sqsClient.sendMessageBatch(sendMessageBatchRequest); • For API details, see SendMessageBatch in AWS SDK for Java 2.x API Reference. PowerShell Tools for PowerShell Example 1: This example sends 2 messages with the specified attributes and message bodies to the specified queue. Delivery is delayed for 15 seconds for the first message and 10 seconds for the second message. $student1NameAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $student1NameAttributeValue.DataType = "String" $student1NameAttributeValue.StringValue = "John Doe" $student1GradeAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $student1GradeAttributeValue.DataType = "Number" $student1GradeAttributeValue.StringValue = "89" $student2NameAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $student2NameAttributeValue.DataType = "String" $student2NameAttributeValue.StringValue = "Jane Doe" $student2GradeAttributeValue = New-Object Amazon.SQS.Model.MessageAttributeValue $student2GradeAttributeValue.DataType = "Number" $student2GradeAttributeValue.StringValue = "93" $message1 = New-Object Amazon.SQS.Model.SendMessageBatchRequestEntry $message1.DelaySeconds = 15 $message1.Id = "FirstMessage" $message1.MessageAttributes.Add("StudentName", $student1NameAttributeValue) $message1.MessageAttributes.Add("StudentGrade", $student1GradeAttributeValue) $message1.MessageBody = "Information about John Doe's grade." $message2 = New-Object Amazon.SQS.Model.SendMessageBatchRequestEntry Actions 385 Amazon Simple Queue Service Developer Guide $message2.DelaySeconds = 10 $message2.Id = "SecondMessage" $message2.MessageAttributes.Add("StudentName", $student2NameAttributeValue) $message2.MessageAttributes.Add("StudentGrade", $student2GradeAttributeValue) $message2.MessageBody = "Information about Jane Doe's grade." Send-SQSMessageBatch -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/ MyQueue -Entry $message1, $message2 Output: Failed Successful ------ ---------- {} {FirstMessage, SecondMessage} • For API details, see SendMessageBatch in AWS Tools for PowerShell Cmdlet Reference. Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. def send_messages(queue, messages): """ 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 queue: The queue to receive the messages. :param messages: The messages to send to the queue. These are simplified to contain only the message body and attributes. Actions 386 Amazon Simple Queue Service Developer Guide :return: The response from SQS that contains the list of successful and failed messages. """ try: entries = [ { "Id": str(ind), "MessageBody": msg["body"], "MessageAttributes": msg["attributes"], } for ind, msg in enumerate(messages) ] response = queue.send_messages(Entries=entries) if "Successful" in response: for msg_meta in response["Successful"]: logger.info( "Message sent: %s: %s", msg_meta["MessageId"], messages[int(msg_meta["Id"])]["body"], ) if "Failed" in response: for msg_meta in response["Failed"]: logger.warning( "Failed to send: %s: %s", msg_meta["MessageId"], messages[int(msg_meta["Id"])]["body"], ) except ClientError as error: logger.exception("Send messages failed to queue: %s", queue) raise error else: return response • For API details, see SendMessageBatch in AWS SDK for Python (Boto3) API Reference. Actions 387 Amazon Simple Queue Service Ruby SDK for Ruby Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. require 'aws-sdk-sqs' require 'aws-sdk-sts' # # @param sqs_client [Aws::SQS::Client] An initialized Amazon SQS client. # @param queue_url [String] The URL of the queue. # @param entries [Hash] The contents of the messages to be sent, # in the correct format. # @return [Boolean] true if the messages were sent; otherwise, false. # @example # exit 1 unless messages_sent?( # Aws::SQS::Client.new(region: 'us-west-2'), # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue', # [ # { # id: 'Message1', # message_body: 'This is the first message.' # }, # { # id: 'Message2', # message_body: 'This is the second message.' # } # ] # ) def messages_sent?(sqs_client, queue_url, entries) sqs_client.send_message_batch( queue_url: queue_url, entries: entries ) true rescue StandardError => e Actions 388 Amazon Simple Queue Service Developer Guide puts "Error sending messages: #{e.message}" false end # Full example call: # Replace us-west-2 with the AWS Region you're using for Amazon SQS. def run_me region = 'us-west-2' queue_name = 'my-queue' entries = [ { id: 'Message1', message_body: 'This is the first message.' }, { id: 'Message2', message_body: 'This is the second message.' } ] sts_client = Aws::STS::Client.new(region: region) # For example: # 'https://sqs.us-west-2.amazonaws.com/111111111111/my-queue' queue_url = "https://sqs.#{region}.amazonaws.com/ #{sts_client.get_caller_identity.account}/#{queue_name}" sqs_client = Aws::SQS::Client.new(region: region) puts "Sending messages to the queue named '#{queue_name}'..." if messages_sent?(sqs_client, queue_url, entries) puts 'Messages sent.' else puts 'Messages not sent.' end end • For API details, see SendMessageBatch in AWS SDK for Ruby API Reference. Actions 389 Amazon Simple Queue Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use SetQueueAttributes with an AWS SDK or CLI The following code examples show how to use SetQueueAttributes. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Publish messages to queues .NET SDK for .NET Note There's more on GitHub. Find the
|
sqs-dg-105
|
sqs-dg.pdf
| 105 |
389 Amazon Simple Queue Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Use SetQueueAttributes with an AWS SDK or CLI The following code examples show how to use SetQueueAttributes. Action examples are code excerpts from larger programs and must be run in context. You can see this action in context in the following code example: • Publish messages to queues .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Set the policy attribute of a queue for a topic. /// <summary> /// Set the policy attribute of a queue for a topic. /// </summary> /// <param name="queueArn">The ARN of the queue.</param> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="queueUrl">The url for the queue.</param> /// <returns>True if successful.</returns> public async Task<bool> SetQueuePolicyForTopic(string queueArn, string topicArn, string queueUrl) { var queuePolicy = "{" + "\"Version\": \"2012-10-17\"," + "\"Statement\": [{" + "\"Effect\": \"Allow\"," + "\"Principal\": {" + $"\"Service\": " + "\"sns.amazonaws.com\"" + Actions 390 Amazon Simple Queue Service Developer Guide "}," + "\"Action\": \"sqs:SendMessage\"," + $"\"Resource\": \"{queueArn}\"," + "\"Condition\": {" + "\"ArnEquals\": {" + $"\"aws:SourceArn\": \"{topicArn}\"" + "}" + "}" + "}]" + "}"; var attributesResponse = await _amazonSQSClient.SetQueueAttributesAsync( new SetQueueAttributesRequest() { QueueUrl = queueUrl, Attributes = new Dictionary<string, string>() { { "Policy", queuePolicy } } }); return attributesResponse.HttpStatusCode == HttpStatusCode.OK; } • For API details, see SetQueueAttributes in AWS SDK for .NET API Reference. C++ SDK for C++ Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Set the value for an attribute in an Amazon Simple Queue Service (Amazon SQS) queue. /*! \param queueUrl: An Amazon SQS queue URL. Actions 391 Amazon Simple Queue Service Developer Guide \param attributeName: An attribute name enum. \param attribute: The attribute value as a string. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::setQueueAttributes(const Aws::String &queueURL, Aws::SQS::Model::QueueAttributeName attributeName, const Aws::String &attribute, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::SetQueueAttributesRequest request; request.SetQueueUrl(queueURL); request.AddAttributes( attributeName, attribute); const Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes( request); if (outcome.IsSuccess()) { std::cout << "Successfully set the attribute " << Aws::SQS::Model::QueueAttributeNameMapper::GetNameForQueueAttributeName( attributeName) << " with value " << attribute << " in queue " << queueURL << "." << std::endl; } else { std::cout << "Error setting attribute for queue " << queueURL << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } Configure a dead-letter queue. Aws::Client::ClientConfiguration clientConfig; Actions 392 Amazon Simple Queue Service Developer Guide // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Connect an Amazon Simple Queue Service (Amazon SQS) queue to an associated //! dead-letter queue. /*! \param srcQueueUrl: An Amazon SQS queue URL. \param deadLetterQueueARN: The Amazon Resource Name (ARN) of an Amazon SQS dead-letter queue. \param maxReceiveCount: The max receive count of a message before it is sent to the dead-letter queue. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::setDeadLetterQueue(const Aws::String &srcQueueUrl, const Aws::String &deadLetterQueueARN, int maxReceiveCount, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::String redrivePolicy = MakeRedrivePolicy(deadLetterQueueARN, maxReceiveCount); Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::SQS::Model::SetQueueAttributesRequest request; request.SetQueueUrl(srcQueueUrl); request.AddAttributes( Aws::SQS::Model::QueueAttributeName::RedrivePolicy, redrivePolicy); const Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes(request); if (outcome.IsSuccess()) { std::cout << "Successfully set dead letter queue for queue " << srcQueueUrl << " to " << deadLetterQueueARN << std::endl; } else { std::cerr << "Error setting dead letter queue for queue " << srcQueueUrl << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } Actions 393 Amazon Simple Queue Service Developer Guide //! Make a redrive policy for a dead-letter queue. /*! \param queueArn: An Amazon SQS ARN for the dead-letter queue. \param maxReceiveCount: The max receive count of a message before it is sent to the dead-letter queue. \return Aws::String: Policy as JSON string. */ Aws::String MakeRedrivePolicy(const Aws::String &queueArn, int maxReceiveCount) { Aws::Utils::Json::JsonValue redrive_arn_entry; redrive_arn_entry.AsString(queueArn); Aws::Utils::Json::JsonValue max_msg_entry; max_msg_entry.AsInteger(maxReceiveCount); Aws::Utils::Json::JsonValue policy_map; policy_map.WithObject("deadLetterTargetArn", redrive_arn_entry); policy_map.WithObject("maxReceiveCount", max_msg_entry); return policy_map.View().WriteReadable(); } Configure an Amazon SQS queue to use long polling. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Set the wait time for an Amazon Simple Queue Service (Amazon SQS) queue poll. /*! \param queueUrl: An Amazon SQS queue URL. \param pollTimeSeconds: The receive message wait time in seconds. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::setQueueLongPollingAttribute(const Aws::String &queueURL, const Aws::String &pollTimeSeconds, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Actions 394 Amazon Simple Queue Service Developer Guide Aws::SQS::Model::SetQueueAttributesRequest request; request.SetQueueUrl(queueURL); request.AddAttributes( Aws::SQS::Model::QueueAttributeName::ReceiveMessageWaitTimeSeconds, pollTimeSeconds); const Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes( request); if (outcome.IsSuccess())
|
sqs-dg-106
|
sqs-dg.pdf
| 106 |
Amazon SQS queue to use long polling. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Set the wait time for an Amazon Simple Queue Service (Amazon SQS) queue poll. /*! \param queueUrl: An Amazon SQS queue URL. \param pollTimeSeconds: The receive message wait time in seconds. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SQS::setQueueLongPollingAttribute(const Aws::String &queueURL, const Aws::String &pollTimeSeconds, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SQS::SQSClient sqsClient(clientConfiguration); Actions 394 Amazon Simple Queue Service Developer Guide Aws::SQS::Model::SetQueueAttributesRequest request; request.SetQueueUrl(queueURL); request.AddAttributes( Aws::SQS::Model::QueueAttributeName::ReceiveMessageWaitTimeSeconds, pollTimeSeconds); const Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes( request); if (outcome.IsSuccess()) { std::cout << "Successfully updated long polling time for queue " << queueURL << " to " << pollTimeSeconds << std::endl; } else { std::cout << "Error updating long polling time for queue " << queueURL << ": " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); } • For API details, see SetQueueAttributes in AWS SDK for C++ API Reference. CLI AWS CLI To set queue attributes This example sets the specified queue to a delivery delay of 10 seconds, a maximum message size of 128 KB (128 KB * 1,024 bytes), a message retention period of 3 days (3 days * 24 hours * 60 minutes * 60 seconds), a receive message wait time of 20 seconds, and a default visibility timeout of 60 seconds. This example also associates the specified dead letter queue with a maximum receive count of 1,000 messages. Command: aws sqs set-queue-attributes --queue-url https://sqs.us- east-1.amazonaws.com/80398EXAMPLE/MyNewQueue --attributes file://set-queue- attributes.json Actions 395 Amazon Simple Queue Service Developer Guide Input file (set-queue-attributes.json): { "DelaySeconds": "10", "MaximumMessageSize": "131072", "MessageRetentionPeriod": "259200", "ReceiveMessageWaitTimeSeconds": "20", "RedrivePolicy": "{\"deadLetterTargetArn\":\"arn:aws:sqs:us- east-1:80398EXAMPLE:MyDeadLetterQueue\",\"maxReceiveCount\":\"1000\"}", "VisibilityTimeout": "60" } Output: None. • For API details, see SetQueueAttributes in AWS CLI Command Reference. Go SDK for Go V2 Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import ( "context" "encoding/json" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" ) // SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions Actions 396 Amazon Simple Queue Service Developer Guide // used in the examples. type SqsActions struct { SqsClient *sqs.Client } // AttachSendMessagePolicy uses the SetQueueAttributes action to attach a policy to an // Amazon SQS queue that allows the specified Amazon SNS topic to send messages to the // queue. func (actor SqsActions) AttachSendMessagePolicy(ctx context.Context, queueUrl string, queueArn string, topicArn string) error { policyDoc := PolicyDocument{ Version: "2012-10-17", Statement: []PolicyStatement{{ Effect: "Allow", Action: "sqs:SendMessage", Principal: map[string]string{"Service": "sns.amazonaws.com"}, Resource: aws.String(queueArn), Condition: PolicyCondition{"ArnEquals": map[string]string{"aws:SourceArn": topicArn}}, }}, } policyBytes, err := json.Marshal(policyDoc) if err != nil { log.Printf("Couldn't create policy document. Here's why: %v\n", err) return err } _, err = actor.SqsClient.SetQueueAttributes(ctx, &sqs.SetQueueAttributesInput{ Attributes: map[string]string{ string(types.QueueAttributeNamePolicy): string(policyBytes), }, QueueUrl: aws.String(queueUrl), }) if err != nil { log.Printf("Couldn't set send message policy on queue %v. Here's why: %v\n", queueUrl, err) } return err } // PolicyDocument defines a policy document as a Go struct that can be serialized Actions 397 Amazon Simple Queue Service // to JSON. type PolicyDocument struct { Version string Statement []PolicyStatement } Developer Guide // PolicyStatement defines a statement in a policy document. type PolicyStatement struct { Effect string Action string Principal map[string]string `json:",omitempty"` Resource *string `json:",omitempty"` Condition PolicyCondition `json:",omitempty"` } // PolicyCondition defines a condition in a policy. type PolicyCondition map[string]map[string]string • For API details, see SetQueueAttributes in AWS SDK for Go API Reference. 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. Configure an Amazon SQS to use server-side encryption (SSE) using a custom KMS key. public static void addEncryption(String queueName, String kmsMasterKeyAlias) { SqsClient sqsClient = SqsClient.create(); GetQueueUrlRequest urlRequest = GetQueueUrlRequest.builder() .queueName(queueName) .build(); Actions 398 Amazon Simple Queue Service Developer Guide GetQueueUrlResponse getQueueUrlResponse; try { getQueueUrlResponse = sqsClient.getQueueUrl(urlRequest); } catch (QueueDoesNotExistException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } String queueUrl = getQueueUrlResponse.queueUrl(); Map<QueueAttributeName, String> attributes = Map.of( QueueAttributeName.KMS_MASTER_KEY_ID, kmsMasterKeyAlias, QueueAttributeName.KMS_DATA_KEY_REUSE_PERIOD_SECONDS, "140" // Set the data key reuse period to 140 seconds. ); // This is how long SQS can reuse the data key before requesting a new one from KMS. SetQueueAttributesRequest attRequest = SetQueueAttributesRequest.builder() .queueUrl(queueUrl) .attributes(attributes) .build(); try { sqsClient.setQueueAttributes(attRequest); LOGGER.info("The attributes have been applied to {}", queueName); } catch (InvalidAttributeNameException | InvalidAttributeValueException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } finally { sqsClient.close(); } } • For API details, see SetQueueAttributes in AWS SDK for Java 2.x API Reference. Actions 399 Amazon Simple Queue Service JavaScript SDK for JavaScript (v3) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { SetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue-url"; export const main =
|
sqs-dg-107
|
sqs-dg.pdf
| 107 |
.build(); try { sqsClient.setQueueAttributes(attRequest); LOGGER.info("The attributes have been applied to {}", queueName); } catch (InvalidAttributeNameException | InvalidAttributeValueException e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } finally { sqsClient.close(); } } • For API details, see SetQueueAttributes in AWS SDK for Java 2.x API Reference. Actions 399 Amazon Simple Queue Service JavaScript SDK for JavaScript (v3) Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import { SetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue-url"; export const main = async (queueUrl = SQS_QUEUE_URL) => { const command = new SetQueueAttributesCommand({ QueueUrl: queueUrl, Attributes: { DelaySeconds: "1", }, }); const response = await client.send(command); console.log(response); return response; }; Configure an Amazon SQS queue to use long polling. import { SetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; export const main = async (queueUrl = SQS_QUEUE_URL) => { const command = new SetQueueAttributesCommand({ Attributes: { ReceiveMessageWaitTimeSeconds: "20", }, QueueUrl: queueUrl, Actions 400 Amazon Simple Queue Service }); Developer Guide const response = await client.send(command); console.log(response); return response; }; Configure a dead-letter queue. import { SetQueueAttributesCommand, SQSClient } from "@aws-sdk/client-sqs"; const client = new SQSClient({}); const SQS_QUEUE_URL = "queue_url"; const DEAD_LETTER_QUEUE_ARN = "dead_letter_queue_arn"; export const main = async ( queueUrl = SQS_QUEUE_URL, deadLetterQueueArn = DEAD_LETTER_QUEUE_ARN, ) => { const command = new SetQueueAttributesCommand({ Attributes: { RedrivePolicy: JSON.stringify({ // Amazon SQS supports dead-letter queues (DLQ), which other // queues (source queues) can target for messages that can't // be processed (consumed) successfully. // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/ SQSDeveloperGuide/sqs-dead-letter-queues.html deadLetterTargetArn: deadLetterQueueArn, maxReceiveCount: "10", }), }, QueueUrl: queueUrl, }); const response = await client.send(command); console.log(response); return response; }; • For API details, see SetQueueAttributes in AWS SDK for JavaScript API Reference. Actions 401 Amazon Simple Queue Service PowerShell Tools for PowerShell Developer Guide Example 1: This example shows how to set a policy subscribing a queue to an SNS topic. When a message is published to the topic, a message is sent to the subscribed queue. # create the queue and topic to be associated $qurl = New-SQSQueue -QueueName "myQueue" $topicarn = New-SNSTopic -Name "myTopic" # get the queue ARN to inject into the policy; it will be returned # in the output's QueueARN member but we need to put it into a variable # so text expansion in the policy string takes effect $qarn = (Get-SQSQueueAttribute -QueueUrl $qurl -AttributeName "QueueArn").QueueARN # construct the policy and inject arns $policy = @" { "Version": "2008-10-17", "Id": "$qarn/SQSPOLICY", "Statement": [ { "Sid": "1", "Effect": "Allow", "Principal": "*", "Action": "SQS:SendMessage", "Resource": "$qarn", "Condition": { "ArnEquals": { "aws:SourceArn": "$topicarn" } } } ] } "@ # set the policy Set-SQSQueueAttribute -QueueUrl $qurl -Attribute @{ Policy=$policy } Example 2: This example sets the specified attributes for the specified queue. Actions 402 Amazon Simple Queue Service Developer Guide Set-SQSQueueAttribute -Attribute @{"DelaySeconds" = "10"; "MaximumMessageSize" = "131072"} -QueueUrl https://sqs.us-east-1.amazonaws.com/80398EXAMPLE/MyQueue • For API details, see SetQueueAttributes in AWS Tools for PowerShell Cmdlet Reference. Swift SDK for Swift Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. import AWSSQS let config = try await SQSClient.SQSClientConfiguration(region: region) let sqsClient = SQSClient(config: config) do { _ = try await sqsClient.setQueueAttributes( input: SetQueueAttributesInput( attributes: [ "MaximumMessageSize": "\(maxSize)" ], queueUrl: url ) ) } catch _ as AWSSQS.InvalidAttributeValue { print("Invalid maximum message size: \(maxSize) kB.") } • For API details, see SetQueueAttributes in AWS SDK for Swift API reference. For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Actions 403 Amazon Simple Queue Service Developer Guide Scenarios for Amazon SQS using AWS SDKs The following code examples show you how to implement common scenarios in Amazon SQS with AWS SDKs. These scenarios show you how to accomplish specific tasks by calling multiple functions within Amazon SQS or combined with other AWS services. Each scenario includes a link to the complete source code, where you can find instructions on how to set up and run the code. Scenarios target an intermediate level of experience to help you understand service actions in context. Examples • Create a web application that sends and retrieves messages by using Amazon SQS • Create a messenger application with Step Functions • Create an Amazon Textract explorer application • Create and publish to a FIFO Amazon SNS topic using an AWS SDK • Detect people and objects in a video with Amazon Rekognition using an AWS SDK • Receive and process Amazon S3 event notifications by using an AWS SDK • Publish Amazon SNS messages to Amazon SQS queues using an AWS SDK
|
sqs-dg-108
|
sqs-dg.pdf
| 108 |
Scenarios target an intermediate level of experience to help you understand service actions in context. Examples • Create a web application that sends and retrieves messages by using Amazon SQS • Create a messenger application with Step Functions • Create an Amazon Textract explorer application • Create and publish to a FIFO Amazon SNS topic using an AWS SDK • Detect people and objects in a video with Amazon Rekognition using an AWS SDK • Receive and process Amazon S3 event notifications by using an AWS SDK • Publish Amazon SNS messages to Amazon SQS queues using an AWS SDK • Send and receive batches of messages with Amazon SQS using an AWS SDK • Use the AWS Message Processing Framework for .NET to publish and receive Amazon SQS messages • Use the Amazon SQS Java Messaging Library to work with the Java Message Service (JMS) interface for Amazon SQS • Work with queue tags and Amazon SQS using an AWS SDK Create a web application that sends and retrieves messages by using Amazon SQS The following code examples show how to create a messaging application by using Amazon SQS. Java SDK for Java 2.x Shows how to use the Amazon SQS API to develop a Spring REST API that sends and retrieves messages. Scenarios 404 Amazon Simple Queue Service Developer Guide For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Comprehend • Amazon SQS Kotlin SDK for Kotlin Shows how to use the Amazon SQS API to develop a Spring REST API that sends and retrieves messages. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Comprehend • Amazon SQS For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Create a messenger application with Step Functions The following code example shows how to create an AWS Step Functions messenger application that retrieves message records from a database table. Python SDK for Python (Boto3) Shows how to use the AWS SDK for Python (Boto3) with AWS Step Functions to create a messenger application that retrieves message records from an Amazon DynamoDB table and sends them with Amazon Simple Queue Service (Amazon SQS). The state machine integrates with an AWS Lambda function to scan the database for unsent messages. Create a messenger application 405 Amazon Simple Queue Service Developer Guide • Create a state machine that retrieves and updates message records from an Amazon DynamoDB table. • Update the state machine definition to also send messages to Amazon Simple Queue Service (Amazon SQS). • Start and stop state machine runs. • Connect to Lambda, DynamoDB, and Amazon SQS from a state machine by using service integrations. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • DynamoDB • Lambda • Amazon SQS • Step Functions For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Create an Amazon Textract explorer application The following code examples show how to explore Amazon Textract output through an interactive application. JavaScript SDK for JavaScript (v3) Shows how to use the AWS SDK for JavaScript to build a React application that uses Amazon Textract to extract data from a document image and display it in an interactive web page. This example runs in a web browser and requires an authenticated Amazon Cognito identity for credentials. It uses Amazon Simple Storage Service (Amazon S3) for storage, and for notifications it polls an Amazon Simple Queue Service (Amazon SQS) queue that is subscribed to an Amazon Simple Notification Service (Amazon SNS) topic. Create an Amazon Textract explorer application 406 Amazon Simple Queue Service Developer Guide For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Cognito Identity • Amazon S3 • Amazon SNS • Amazon SQS • Amazon Textract Python SDK for Python (Boto3) Shows how to use the AWS SDK for Python (Boto3) with Amazon Textract to detect text, form, and table elements in a document image. The input image and Amazon Textract output are shown in a Tkinter application that lets you explore the detected elements. • Submit a document image to Amazon Textract and explore the output of detected elements. • Submit images directly to Amazon Textract or through an Amazon
|
sqs-dg-109
|
sqs-dg.pdf
| 109 |
full example on GitHub. Services used in this example • Amazon Cognito Identity • Amazon S3 • Amazon SNS • Amazon SQS • Amazon Textract Python SDK for Python (Boto3) Shows how to use the AWS SDK for Python (Boto3) with Amazon Textract to detect text, form, and table elements in a document image. The input image and Amazon Textract output are shown in a Tkinter application that lets you explore the detected elements. • Submit a document image to Amazon Textract and explore the output of detected elements. • Submit images directly to Amazon Textract or through an Amazon Simple Storage Service (Amazon S3) bucket. • Use asynchronous APIs to start a job that publishes a notification to an Amazon Simple Notification Service (Amazon SNS) topic when the job completes. • Poll an Amazon Simple Queue Service (Amazon SQS) queue for a job completion message and display the results. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Cognito Identity • Amazon S3 • Amazon SNS • Amazon SQS • Amazon Textract Create an Amazon Textract explorer application 407 Amazon Simple Queue Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Create and publish to a FIFO Amazon SNS topic using an AWS SDK The following code examples show how to create and publish to a FIFO Amazon SNS topic. 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. This example • creates an Amazon SNS FIFO topic, two Amazon SQS FIFO queues, and one Standard queue. • subscribes the queues to the topic and publishes a message to the topic. The test verifies the receipt of the message to each queue. The complete example also shows the addition of access policies and deletes the resources at the end. public class PriceUpdateExample { public final static SnsClient snsClient = SnsClient.create(); public final static SqsClient sqsClient = SqsClient.create(); public static void main(String[] args) { final String usage = "\n" + "Usage: " + " <topicName> <wholesaleQueueFifoName> <retailQueueFifoName> <analyticsQueueName>\n\n" + "Where:\n" + " fifoTopicName - The name of the FIFO topic that you want to create. \n\n" + " wholesaleQueueARN - The name of a SQS FIFO queue that will be created for the wholesale consumer. \n\n" Create and publish to a FIFO topic 408 Amazon Simple Queue Service + Developer Guide " retailQueueARN - The name of a SQS FIFO queue that will created for the retail consumer. \n\n" + " analyticsQueueARN - The name of a SQS standard queue that will be created for the analytics consumer. \n\n"; if (args.length != 4) { System.out.println(usage); System.exit(1); } final String fifoTopicName = args[0]; final String wholeSaleQueueName = args[1]; final String retailQueueName = args[2]; final String analyticsQueueName = args[3]; // For convenience, the QueueData class holds metadata about a queue: ARN, URL, // name and type. List<QueueData> queues = List.of( new QueueData(wholeSaleQueueName, QueueType.FIFO), new QueueData(retailQueueName, QueueType.FIFO), new QueueData(analyticsQueueName, QueueType.Standard)); // Create queues. createQueues(queues); // Create a topic. String topicARN = createFIFOTopic(fifoTopicName); // Subscribe each queue to the topic. subscribeQueues(queues, topicARN); // Allow the newly created topic to send messages to the queues. addAccessPolicyToQueuesFINAL(queues, topicARN); // Publish a sample price update message with payload. publishPriceUpdate(topicARN, "{\"product\": 214, \"price\": 79.99}", "Consumables"); // Clean up resources. deleteSubscriptions(queues); deleteQueues(queues); deleteTopic(topicARN); } Create and publish to a FIFO topic 409 Amazon Simple Queue Service Developer Guide public static String createFIFOTopic(String topicName) { try { // Create a FIFO topic by using the SNS service client. Map<String, String> topicAttributes = Map.of( "FifoTopic", "true", "ContentBasedDeduplication", "false", "FifoThroughputScope", "MessageGroup"); CreateTopicRequest topicRequest = CreateTopicRequest.builder() .name(topicName) .attributes(topicAttributes) .build(); CreateTopicResponse response = snsClient.createTopic(topicRequest); String topicArn = response.topicArn(); System.out.println("The topic ARN is" + topicArn); return topicArn; } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static void subscribeQueues(List<QueueData> queues, String topicARN) { queues.forEach(queue -> { SubscribeRequest subscribeRequest = SubscribeRequest.builder() .topicArn(topicARN) .endpoint(queue.queueARN) .protocol("sqs") .build(); // Subscribe to the endpoint by using the SNS service client. // Only Amazon SQS queues can receive notifications from an Amazon SNS FIFO // topic. SubscribeResponse subscribeResponse = snsClient.subscribe(subscribeRequest); System.out.println("The queue [" + queue.queueARN + "] subscribed to the topic [" + topicARN + "]"); queue.subscriptionARN = subscribeResponse.subscriptionArn(); Create and publish to a FIFO topic 410 Amazon Simple Queue Service }); } Developer Guide public static void publishPriceUpdate(String topicArn, String payload, String groupId) { try { // Create and publish a message that updates the wholesale price. String subject = "Price Update"; String dedupId = UUID.randomUUID().toString(); String attributeName = "business"; String attributeValue =
|
sqs-dg-110
|
sqs-dg.pdf
| 110 |
endpoint by using the SNS service client. // Only Amazon SQS queues can receive notifications from an Amazon SNS FIFO // topic. SubscribeResponse subscribeResponse = snsClient.subscribe(subscribeRequest); System.out.println("The queue [" + queue.queueARN + "] subscribed to the topic [" + topicARN + "]"); queue.subscriptionARN = subscribeResponse.subscriptionArn(); Create and publish to a FIFO topic 410 Amazon Simple Queue Service }); } Developer Guide public static void publishPriceUpdate(String topicArn, String payload, String groupId) { try { // Create and publish a message that updates the wholesale price. String subject = "Price Update"; String dedupId = UUID.randomUUID().toString(); String attributeName = "business"; String attributeValue = "wholesale"; MessageAttributeValue msgAttValue = MessageAttributeValue.builder() .dataType("String") .stringValue(attributeValue) .build(); Map<String, MessageAttributeValue> attributes = new HashMap<>(); attributes.put(attributeName, msgAttValue); PublishRequest pubRequest = PublishRequest.builder() .topicArn(topicArn) .subject(subject) .message(payload) .messageGroupId(groupId) .messageDeduplicationId(dedupId) .messageAttributes(attributes) .build(); final PublishResponse response = snsClient.publish(pubRequest); System.out.println(response.messageId()); System.out.println(response.sequenceNumber()); System.out.println("Message was published to " + topicArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • CreateTopic Create and publish to a FIFO topic 411 Amazon Simple Queue Service Developer Guide • Publish • Subscribe Python SDK for Python (Boto3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create an Amazon SNS FIFO topic, subscribe Amazon SQS FIFO and standard queues to the topic, and publish a message to the topic. def usage_demo(): """Shows how to subscribe queues to a FIFO topic.""" print("-" * 88) print("Welcome to the `Subscribe queues to a FIFO topic` demo!") print("-" * 88) sns = boto3.resource("sns") sqs = boto3.resource("sqs") fifo_topic_wrapper = FifoTopicWrapper(sns) sns_wrapper = SnsWrapper(sns) prefix = "sqs-subscribe-demo-" queues = set() subscriptions = set() wholesale_queue = sqs.create_queue( QueueName=prefix + "wholesale.fifo", Attributes={ "MaximumMessageSize": str(4096), "ReceiveMessageWaitTimeSeconds": str(10), "VisibilityTimeout": str(300), "FifoQueue": str(True), "ContentBasedDeduplication": str(True), }, ) Create and publish to a FIFO topic 412 Amazon Simple Queue Service Developer Guide queues.add(wholesale_queue) print(f"Created FIFO queue with URL: {wholesale_queue.url}.") retail_queue = sqs.create_queue( QueueName=prefix + "retail.fifo", Attributes={ "MaximumMessageSize": str(4096), "ReceiveMessageWaitTimeSeconds": str(10), "VisibilityTimeout": str(300), "FifoQueue": str(True), "ContentBasedDeduplication": str(True), }, ) queues.add(retail_queue) print(f"Created FIFO queue with URL: {retail_queue.url}.") analytics_queue = sqs.create_queue(QueueName=prefix + "analytics", Attributes={}) queues.add(analytics_queue) print(f"Created standard queue with URL: {analytics_queue.url}.") topic = fifo_topic_wrapper.create_fifo_topic("price-updates-topic.fifo") print(f"Created FIFO topic: {topic.attributes['TopicArn']}.") for q in queues: fifo_topic_wrapper.add_access_policy(q, topic.attributes["TopicArn"]) print(f"Added access policies for topic: {topic.attributes['TopicArn']}.") for q in queues: sub = fifo_topic_wrapper.subscribe_queue_to_topic( topic, q.attributes["QueueArn"] ) subscriptions.add(sub) print(f"Subscribed queues to topic: {topic.attributes['TopicArn']}.") input("Press Enter to publish a message to the topic.") message_id = fifo_topic_wrapper.publish_price_update( topic, '{"product": 214, "price": 79.99}', "Consumables" ) print(f"Published price update with message ID: {message_id}.") Create and publish to a FIFO topic 413 Amazon Simple Queue Service Developer Guide # Clean up the subscriptions, queues, and topic. input("Press Enter to clean up resources.") for s in subscriptions: sns_wrapper.delete_subscription(s) sns_wrapper.delete_topic(topic) for q in queues: fifo_topic_wrapper.delete_queue(q) print(f"Deleted subscriptions, queues, and topic.") print("Thanks for watching!") print("-" * 88) class FifoTopicWrapper: """Encapsulates Amazon SNS FIFO topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource def create_fifo_topic(self, topic_name): """ Create a FIFO topic. Topic names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores, and hyphens, and must be between 1 and 256 characters long. For a FIFO topic, the name must end with the .fifo suffix. :param topic_name: The name for the topic. :return: The new topic. """ try: topic = self.sns_resource.create_topic( Name=topic_name, Attributes={ "FifoTopic": str(True), Create and publish to a FIFO topic 414 Amazon Simple Queue Service Developer Guide "ContentBasedDeduplication": str(False), "FifoThroughputScope": "MessageGroup", }, ) logger.info("Created FIFO topic with name=%s.", topic_name) return topic except ClientError as error: logger.exception("Couldn't create topic with name=%s!", topic_name) raise error @staticmethod def add_access_policy(queue, topic_arn): """ Add the necessary access policy to a queue, so it can receive messages from a topic. :param queue: The queue resource. :param topic_arn: The ARN of the topic. :return: None. """ try: queue.set_attributes( Attributes={ "Policy": json.dumps( { "Version": "2012-10-17", "Statement": [ { "Sid": "test-sid", "Effect": "Allow", "Principal": {"AWS": "*"}, "Action": "SQS:SendMessage", "Resource": queue.attributes["QueueArn"], "Condition": { "ArnLike": {"aws:SourceArn": topic_arn} }, } ], } ) } ) logger.info("Added trust policy to the queue.") Create and publish to a FIFO topic 415 Amazon Simple Queue Service Developer Guide except ClientError as error: logger.exception("Couldn't add trust policy to the queue!") raise error @staticmethod def subscribe_queue_to_topic(topic, queue_arn): """ Subscribe a queue to a topic. :param topic: The topic resource. :param queue_arn: The ARN of the queue. :return: The subscription resource. """ try: subscription = topic.subscribe( Protocol="sqs", Endpoint=queue_arn, ) logger.info("The queue is subscribed to the topic.") return subscription except ClientError as error: logger.exception("Couldn't subscribe queue to topic!") raise error @staticmethod def publish_price_update(topic, payload, group_id): """ Compose and publish a message that updates the wholesale price. :param topic: The topic to publish to. :param payload: The message to publish. :param group_id: The group ID for the
|
sqs-dg-111
|
sqs-dg.pdf
| 111 |
logger.exception("Couldn't add trust policy to the queue!") raise error @staticmethod def subscribe_queue_to_topic(topic, queue_arn): """ Subscribe a queue to a topic. :param topic: The topic resource. :param queue_arn: The ARN of the queue. :return: The subscription resource. """ try: subscription = topic.subscribe( Protocol="sqs", Endpoint=queue_arn, ) logger.info("The queue is subscribed to the topic.") return subscription except ClientError as error: logger.exception("Couldn't subscribe queue to topic!") raise error @staticmethod def publish_price_update(topic, payload, group_id): """ Compose and publish a message that updates the wholesale price. :param topic: The topic to publish to. :param payload: The message to publish. :param group_id: The group ID for the message. :return: The ID of the message. """ try: att_dict = {"business": {"DataType": "String", "StringValue": "wholesale"}} dedup_id = uuid.uuid4() response = topic.publish( Subject="Price Update", Message=payload, MessageAttributes=att_dict, Create and publish to a FIFO topic 416 Amazon Simple Queue Service Developer Guide MessageGroupId=group_id, MessageDeduplicationId=str(dedup_id), ) message_id = response["MessageId"] logger.info("Published message to topic %s.", topic.arn) except ClientError as error: logger.exception("Couldn't publish message to topic %s.", topic.arn) raise error return message_id @staticmethod def delete_queue(queue): """ Removes an SQS queue. When run against an AWS account, it can take up to 60 seconds before the queue is actually deleted. :param queue: The queue to delete. :return: None """ try: queue.delete() logger.info("Deleted queue with URL=%s.", queue.url) except ClientError as error: logger.exception("Couldn't delete queue with URL=%s!", queue.url) raise error • For API details, see the following topics in AWS SDK for Python (Boto3) API Reference. • CreateTopic • Publish • Subscribe Create and publish to a FIFO topic 417 Amazon Simple Queue Service SAP ABAP SDK for SAP ABAP Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Create a FIFO topic, subscribe an Amazon SQS FIFO queue to the topic, and publish a message to an Amazon SNS topic. " Creates a FIFO topic. " DATA lt_tpc_attributes TYPE /aws1/ cl_snstopicattrsmap_w=>tt_topicattributesmap. DATA ls_tpc_attributes TYPE /aws1/ cl_snstopicattrsmap_w=>ts_topicattributesmap_maprow. ls_tpc_attributes-key = 'FifoTopic'. ls_tpc_attributes-value = NEW /aws1/cl_snstopicattrsmap_w( iv_value = 'true' ). INSERT ls_tpc_attributes INTO TABLE lt_tpc_attributes. TRY. DATA(lo_create_result) = lo_sns->createtopic( iv_name = iv_topic_name it_attributes = lt_tpc_attributes ). DATA(lv_topic_arn) = lo_create_result->get_topicarn( ). ov_topic_arn = lv_topic_arn. " ov_topic_arn is returned for testing purposes. " MESSAGE 'FIFO topic created' TYPE 'I'. CATCH /aws1/cx_snstopiclimitexcdex. MESSAGE 'Unable to create more topics. You have reached the maximum number of topics allowed.' TYPE 'E'. ENDTRY. " Subscribes an endpoint to an Amazon Simple Notification Service (Amazon SNS) topic. " " Only Amazon Simple Queue Service (Amazon SQS) FIFO queues can be subscribed to an SNS FIFO topic. " TRY. Create and publish to a FIFO topic 418 Amazon Simple Queue Service Developer Guide DATA(lo_subscribe_result) = lo_sns->subscribe( iv_topicarn = lv_topic_arn iv_protocol = 'sqs' iv_endpoint = iv_queue_arn ). DATA(lv_subscription_arn) = lo_subscribe_result->get_subscriptionarn( ). ov_subscription_arn = lv_subscription_arn. " ov_subscription_arn is returned for testing purposes. " MESSAGE 'SQS queue was subscribed to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. CATCH /aws1/cx_snssubscriptionlmte00. MESSAGE 'Unable to create subscriptions. You have reached the maximum number of subscriptions allowed.' TYPE 'E'. ENDTRY. " Publish message to SNS topic. " TRY. DATA lt_msg_attributes TYPE /aws1/ cl_snsmessageattrvalue=>tt_messageattributemap. DATA ls_msg_attributes TYPE /aws1/ cl_snsmessageattrvalue=>ts_messageattributemap_maprow. ls_msg_attributes-key = 'Importance'. ls_msg_attributes-value = NEW /aws1/cl_snsmessageattrvalue( iv_datatype = 'String' iv_stringvalue = 'High' ). INSERT ls_msg_attributes INTO TABLE lt_msg_attributes. DATA(lo_result) = lo_sns->publish( iv_topicarn = lv_topic_arn iv_message = 'The price of your mobile plan has been increased from $19 to $23' iv_subject = 'Changes to mobile plan' iv_messagegroupid = 'Update-2' iv_messagededuplicationid = 'Update-2.1' it_messageattributes = lt_msg_attributes ). ov_message_id = lo_result->get_messageid( ). " ov_message_id is returned for testing purposes. " MESSAGE 'Message was published to SNS topic.' TYPE 'I'. CATCH /aws1/cx_snsnotfoundexception. MESSAGE 'Topic does not exist.' TYPE 'E'. ENDTRY. Create and publish to a FIFO topic 419 Amazon Simple Queue Service Developer Guide • For API details, see the following topics in AWS SDK for SAP ABAP API reference. • CreateTopic • Publish • Subscribe For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Detect people and objects in a video with Amazon Rekognition using an AWS SDK The following code examples show how to detect people and objects in a video with Amazon Rekognition. Java SDK for Java 2.x Shows how to use Amazon Rekognition Java API to create an app to detect faces and objects in videos located in an Amazon Simple Storage Service (Amazon S3) bucket. The app sends the admin an email notification with the results using Amazon Simple Email Service (Amazon SES). For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Rekognition • Amazon S3 • Amazon SES • Amazon
|
sqs-dg-112
|
sqs-dg.pdf
| 112 |
show how to detect people and objects in a video with Amazon Rekognition. Java SDK for Java 2.x Shows how to use Amazon Rekognition Java API to create an app to detect faces and objects in videos located in an Amazon Simple Storage Service (Amazon S3) bucket. The app sends the admin an email notification with the results using Amazon Simple Email Service (Amazon SES). For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Rekognition • Amazon S3 • Amazon SES • Amazon SNS • Amazon SQS Detect people and objects in a video 420 Amazon Simple Queue Service Python SDK for Python (Boto3) Developer Guide Use Amazon Rekognition to detect faces, objects, and people in videos by starting asynchronous detection jobs. This example also configures Amazon Rekognition to notify an Amazon Simple Notification Service (Amazon SNS) topic when jobs complete and subscribes an Amazon Simple Queue Service (Amazon SQS) queue to the topic. When the queue receives a message about a job, the job is retrieved and the results are output. This example is best viewed on GitHub. For complete source code and instructions on how to set up and run, see the full example on GitHub. Services used in this example • Amazon Rekognition • Amazon S3 • Amazon SES • Amazon SNS • Amazon SQS For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Receive and process Amazon S3 event notifications by using an AWS SDK The following code example shows how to work with S3 event notifications in an object-oriented way. 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. Process S3 event notifications 421 Amazon Simple Queue Service Developer Guide This example show how to process S3 notification event by using Amazon SQS. /** * This method receives S3 event notifications by using an SqsAsyncClient. * After the client receives the messages it deserializes the JSON payload and logs them. It uses * the S3EventNotification class (part of the S3 event notification API for Java) to deserialize * the JSON payload and access the messages in an object-oriented way. * * @param queueUrl The URL of the AWS SQS queue that receives the S3 event notifications. * @see <a href="https://sdk.amazonaws.com/java/api/latest/software/amazon/ awssdk/eventnotifications/s3/model/package-summary.html">S3EventNotification API</a>. * <p> * To use S3 event notification serialization/deserialization to objects, add the following * dependency to your Maven pom.xml file. * <dependency> * <groupId>software.amazon.awssdk</groupId> * <artifactId>s3-event-notifications</artifactId> * <version><LATEST></version> * </dependency> * <p> * The S3 event notification API became available with version 2.25.11 of the Java SDK. * <p> * This example shows the use of the API with AWS SQS, but it can be used to process S3 event notifications * in AWS SNS or AWS Lambda as well. * <p> * Note: The S3EventNotification class does not work with messages routed through AWS EventBridge. */ static void processS3Events(String bucketName, String queueUrl, String queueArn) { try { // Configure the bucket to send Object Created and Object Tagging notifications to an existing SQS queue. s3Client.putBucketNotificationConfiguration(b -> b .notificationConfiguration(ncb -> ncb .queueConfigurations(qcb -> qcb Process S3 event notifications 422 Amazon Simple Queue Service Developer Guide .events(Event.S3_OBJECT_CREATED, Event.S3_OBJECT_TAGGING) .queueArn(queueArn))) .bucket(bucketName) ).join(); triggerS3EventNotifications(bucketName); // Wait for event notifications to propagate. Thread.sleep(Duration.ofSeconds(5).toMillis()); boolean didReceiveMessages = true; while (didReceiveMessages) { // Display the number of messages that are available in the queue. sqsClient.getQueueAttributes(b -> b .queueUrl(queueUrl) .attributeNames(QueueAttributeName.APPROXIMATE_NUMBER_OF_MESSAGES) ).thenAccept(attributeResponse -> logger.info("Approximate number of messages in the queue: {}", attributeResponse.attributes().get(QueueAttributeName.APPROXIMATE_NUMBER_OF_MESSAGES))) .join(); // Receive the messages. ReceiveMessageResponse response = sqsClient.receiveMessage(b -> b .queueUrl(queueUrl) ).get(); logger.info("Count of received messages: {}", response.messages().size()); didReceiveMessages = !response.messages().isEmpty(); // Create a collection to hold the received message for deletion // after we log the messages. HashSet<DeleteMessageBatchRequestEntry> messagesToDelete = new HashSet<>(); // Process each message. response.messages().forEach(message -> { logger.info("Message id: {}", message.messageId()); // Deserialize JSON message body to a S3EventNotification object // to access messages in an object-oriented way. Process S3 event notifications 423 Amazon Simple Queue Service Developer Guide S3EventNotification event = S3EventNotification.fromJson(message.body()); // Log the S3 event notification record details. if (event.getRecords() != null) { event.getRecords().forEach(record -> { String eventName = record.getEventName(); String key = record.getS3().getObject().getKey(); logger.info(record.toString()); logger.info("Event name is {} and key is {}", eventName, key); }); } // Add logged messages to collection for batch deletion. messagesToDelete.add(DeleteMessageBatchRequestEntry.builder() .id(message.messageId()) .receiptHandle(message.receiptHandle()) .build()); }); // Delete messages. if (!messagesToDelete.isEmpty()) { sqsClient.deleteMessageBatch(DeleteMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(messagesToDelete) .build() ).join(); } } // End of while block. } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } • For API details, see the following topics in
|
sqs-dg-113
|
sqs-dg.pdf
| 113 |
Amazon Simple Queue Service Developer Guide S3EventNotification event = S3EventNotification.fromJson(message.body()); // Log the S3 event notification record details. if (event.getRecords() != null) { event.getRecords().forEach(record -> { String eventName = record.getEventName(); String key = record.getS3().getObject().getKey(); logger.info(record.toString()); logger.info("Event name is {} and key is {}", eventName, key); }); } // Add logged messages to collection for batch deletion. messagesToDelete.add(DeleteMessageBatchRequestEntry.builder() .id(message.messageId()) .receiptHandle(message.receiptHandle()) .build()); }); // Delete messages. if (!messagesToDelete.isEmpty()) { sqsClient.deleteMessageBatch(DeleteMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(messagesToDelete) .build() ).join(); } } // End of while block. } catch (InterruptedException | ExecutionException e) { throw new RuntimeException(e); } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • DeleteMessageBatch • GetQueueAttributes • PutBucketNotificationConfiguration • ReceiveMessage Process S3 event notifications 424 Amazon Simple Queue Service Developer Guide For a complete list of AWS SDK developer guides and code examples, see Using Amazon SQS with an AWS SDK. This topic also includes information about getting started and details about previous SDK versions. Publish Amazon SNS messages to Amazon SQS queues using an AWS SDK The following code examples show how to: • Create topic (FIFO or non-FIFO). • Subscribe several queues to the topic with an option to apply a filter. • Publish messages to the topic. • Poll the queues for messages received. .NET SDK for .NET Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Run an interactive scenario at a command prompt. /// <summary> /// Console application to run a feature scenario for topics and queues. /// </summary> public static class TopicsAndQueues { private static bool _useFifoTopic = false; private static bool _useContentBasedDeduplication = false; private static string _topicName = null!; private static string _topicArn = null!; private static readonly int _queueCount = 2; private static readonly string[] _queueUrls = new string[_queueCount]; private static readonly string[] _subscriptionArns = new string[_queueCount]; Publish messages to queues 425 Amazon Simple Queue Service Developer Guide private static readonly string[] _tones = { "cheerful", "funny", "serious", "sincere" }; public static SNSWrapper SnsWrapper { get; set; } = null!; public static SQSWrapper SqsWrapper { get; set; } = null!; public static bool UseConsole { get; set; } = true; static async Task Main(string[] args) { // Set up dependency injection for Amazon EventBridge. using var host = Host.CreateDefaultBuilder(args) .ConfigureLogging(logging => logging.AddFilter("System", LogLevel.Debug) .AddFilter<DebugLoggerProvider>("Microsoft", LogLevel.Information) .AddFilter<ConsoleLoggerProvider>("Microsoft", LogLevel.Trace)) .ConfigureServices((_, services) => services.AddAWSService<IAmazonSQS>() .AddAWSService<IAmazonSimpleNotificationService>() .AddTransient<SNSWrapper>() .AddTransient<SQSWrapper>() ) .Build(); ServicesSetup(host); PrintDescription(); await RunScenario(); } /// <summary> /// Populate the services for use within the console application. /// </summary> /// <param name="host">The services host.</param> private static void ServicesSetup(IHost host) { SnsWrapper = host.Services.GetRequiredService<SNSWrapper>(); SqsWrapper = host.Services.GetRequiredService<SQSWrapper>(); } /// <summary> /// Run the scenario for working with topics and queues. /// </summary> /// <returns>True if successful.</returns> Publish messages to queues 426 Amazon Simple Queue Service Developer Guide public static async Task<bool> RunScenario() { try { await SetupTopic(); await SetupQueues(); await PublishMessages(); foreach (var queueUrl in _queueUrls) { var messages = await PollForMessages(queueUrl); if (messages.Any()) { await DeleteMessages(queueUrl, messages); } } await CleanupResources(); Console.WriteLine("Messaging with topics and queues scenario is complete."); return true; } catch (Exception ex) { Console.WriteLine(new string('-', 80)); Console.WriteLine($"There was a problem running the scenario: {ex.Message}"); await CleanupResources(); Console.WriteLine(new string('-', 80)); return false; } } /// <summary> /// Print a description for the tasks in the scenario. /// </summary> /// <returns>Async task.</returns> private static void PrintDescription() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"Welcome to messaging with topics and queues."); Publish messages to queues 427 Amazon Simple Queue Service Developer Guide Console.WriteLine(new string('-', 80)); Console.WriteLine($"In this scenario, you will create an SNS topic and subscribe {_queueCount} SQS queues to the topic." + $"\r\nYou can select from several options for configuring the topic and the subscriptions for the 2 queues." + $"\r\nYou can then post to the topic and see the results in the queues.\r\n"); Console.WriteLine(new string('-', 80)); } /// <summary> /// Set up the SNS topic to be used with the queues. /// </summary> /// <returns>Async task.</returns> private static async Task<string> SetupTopic() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"SNS topics can be configured as FIFO (First-In-First- Out)." + $"\r\nFIFO topics deliver messages in order and support deduplication and message filtering." + $"\r\nYou can then post to the topic and see the results in the queues.\r\n"); _useFifoTopic = GetYesNoResponse("Would you like to work with FIFO topics?"); if (_useFifoTopic) { Console.WriteLine(new string('-', 80)); _topicName = GetUserResponse("Enter a name for your SNS topic: ", "example-topic"); Console.WriteLine( "Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.\r\n"); Console.WriteLine(new string('-', 80)); Console.WriteLine($"Because you have chosen a FIFO topic, deduplication is supported." + $"\r\nDeduplication IDs are either set in the message or automatically generated " + $"\r\nfrom content using a hash function.\r\n" + Publish messages to queues 428 Amazon Simple Queue Service Developer Guide $"\r\nIf a message is successfully published to
|
sqs-dg-114
|
sqs-dg.pdf
| 114 |
the results in the queues.\r\n"); _useFifoTopic = GetYesNoResponse("Would you like to work with FIFO topics?"); if (_useFifoTopic) { Console.WriteLine(new string('-', 80)); _topicName = GetUserResponse("Enter a name for your SNS topic: ", "example-topic"); Console.WriteLine( "Because you have selected a FIFO topic, '.fifo' must be appended to the topic name.\r\n"); Console.WriteLine(new string('-', 80)); Console.WriteLine($"Because you have chosen a FIFO topic, deduplication is supported." + $"\r\nDeduplication IDs are either set in the message or automatically generated " + $"\r\nfrom content using a hash function.\r\n" + Publish messages to queues 428 Amazon Simple Queue Service Developer Guide $"\r\nIf a message is successfully published to an SNS FIFO topic, any message " + $"\r\npublished and determined to have the same deduplication ID, " + $"\r\nwithin the five-minute deduplication interval, is accepted but not delivered.\r\n" + $"\r\nFor more information about deduplication, " + $"\r\nsee https://docs.aws.amazon.com/sns/latest/ dg/fifo-message-dedup.html."); _useContentBasedDeduplication = GetYesNoResponse("Use content-based deduplication instead of entering a deduplication ID?"); Console.WriteLine(new string('-', 80)); } _topicArn = await SnsWrapper.CreateTopicWithName(_topicName, _useFifoTopic, _useContentBasedDeduplication); Console.WriteLine($"Your new topic with the name {_topicName}" + $"\r\nand Amazon Resource Name (ARN) {_topicArn}" + $"\r\nhas been created.\r\n"); Console.WriteLine(new string('-', 80)); return _topicArn; } /// <summary> /// Set up the queues. /// </summary> /// <returns>Async task.</returns> private static async Task SetupQueues() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"Now you will create {_queueCount} Amazon Simple Queue Service (Amazon SQS) queues to subscribe to the topic."); // Repeat this section for each queue. for (int i = 0; i < _queueCount; i++) { var queueName = GetUserResponse("Enter a name for an Amazon SQS queue: ", $"example-queue-{i}"); if (_useFifoTopic) { // Only explain this once. Publish messages to queues 429 Amazon Simple Queue Service Developer Guide if (i == 0) { Console.WriteLine( "Because you have selected a FIFO topic, '.fifo' must be appended to the queue name."); } var queueUrl = await SqsWrapper.CreateQueueWithName(queueName, _useFifoTopic); _queueUrls[i] = queueUrl; Console.WriteLine($"Your new queue with the name {queueName}" + $"\r\nand queue URL {queueUrl}" + $"\r\nhas been created.\r\n"); if (i == 0) { Console.WriteLine( $"The queue URL is used to retrieve the queue ARN,\r\n" + $"which is used to create a subscription."); Console.WriteLine(new string('-', 80)); } var queueArn = await SqsWrapper.GetQueueArnByUrl(queueUrl); if (i == 0) { Console.WriteLine( $"An AWS Identity and Access Management (IAM) policy must be attached to an SQS queue, enabling it to receive\r\n" + $"messages from an SNS topic"); } await SqsWrapper.SetQueuePolicyForTopic(queueArn, _topicArn, queueUrl); await SetupFilters(i, queueArn, queueName); } } Console.WriteLine(new string('-', 80)); } Publish messages to queues 430 Amazon Simple Queue Service /// <summary> Developer Guide /// Set up filters with user options for a queue. /// </summary> /// <param name="queueCount">The number of this queue.</param> /// <param name="queueArn">The ARN of the queue.</param> /// <param name="queueName">The name of the queue.</param> /// <returns>Async Task.</returns> public static async Task SetupFilters(int queueCount, string queueArn, string queueName) { if (_useFifoTopic) { Console.WriteLine(new string('-', 80)); // Only explain this once. if (queueCount == 0) { Console.WriteLine( "Subscriptions to a FIFO topic can have filters." + "If you add a filter to this subscription, then only the filtered messages " + "will be received in the queue."); Console.WriteLine( "For information about message filtering, " + "see https://docs.aws.amazon.com/sns/latest/dg/sns-message- filtering.html"); Console.WriteLine( "For this example, you can filter messages by a" + "TONE attribute."); } var useFilter = GetYesNoResponse($"Filter messages for {queueName}'s subscription to the topic?"); string? filterPolicy = null; if (useFilter) { filterPolicy = CreateFilterPolicy(); } var subscriptionArn = await SnsWrapper.SubscribeTopicWithFilter(_topicArn, filterPolicy, queueArn); _subscriptionArns[queueCount] = subscriptionArn; Publish messages to queues 431 Amazon Simple Queue Service Developer Guide Console.WriteLine( $"The queue {queueName} has been subscribed to the topic {_topicName} " + $"with the subscription ARN {subscriptionArn}"); Console.WriteLine(new string('-', 80)); } } /// <summary> /// Use user input to create a filter policy for a subscription. /// </summary> /// <returns>The serialized filter policy.</returns> public static string CreateFilterPolicy() { Console.WriteLine(new string('-', 80)); Console.WriteLine( $"You can filter messages by one or more of the following" + $"TONE attributes."); List<string> filterSelections = new List<string>(); var selectionNumber = 0; do { Console.WriteLine( $"Enter a number to add a TONE filter, or enter 0 to stop adding filters."); for (int i = 0; i < _tones.Length; i++) { Console.WriteLine($"\t{i + 1}. {_tones[i]}"); } var selection = GetUserResponse("", filterSelections.Any() ? "0" : "1"); int.TryParse(selection, out selectionNumber); if (selectionNumber > 0 && ! filterSelections.Contains(_tones[selectionNumber - 1])) { filterSelections.Add(_tones[selectionNumber - 1]); } } while (selectionNumber != 0); var filters = new Dictionary<string, List<string>> Publish messages to queues 432 Amazon Simple Queue Service { Developer Guide { "tone", filterSelections } }; string filterPolicy = JsonSerializer.Serialize(filters); return filterPolicy; } /// <summary> /// Publish messages using user settings. /// </summary> /// <returns>Async task.</returns> public static async Task PublishMessages() { Console.WriteLine("Now we can publish messages."); var keepSendingMessages = true; string? deduplicationId = null; string? toneAttribute = null; while (keepSendingMessages) { Console.WriteLine(); var message = GetUserResponse("Enter a message to publish.", "This is a sample message"); if (_useFifoTopic) { Console.WriteLine("Because
|
sqs-dg-115
|
sqs-dg.pdf
| 115 |
filterSelections.Contains(_tones[selectionNumber - 1])) { filterSelections.Add(_tones[selectionNumber - 1]); } } while (selectionNumber != 0); var filters = new Dictionary<string, List<string>> Publish messages to queues 432 Amazon Simple Queue Service { Developer Guide { "tone", filterSelections } }; string filterPolicy = JsonSerializer.Serialize(filters); return filterPolicy; } /// <summary> /// Publish messages using user settings. /// </summary> /// <returns>Async task.</returns> public static async Task PublishMessages() { Console.WriteLine("Now we can publish messages."); var keepSendingMessages = true; string? deduplicationId = null; string? toneAttribute = null; while (keepSendingMessages) { Console.WriteLine(); var message = GetUserResponse("Enter a message to publish.", "This is a sample message"); if (_useFifoTopic) { Console.WriteLine("Because you are using a FIFO topic, you must set a message group ID." + "\r\nAll messages within the same group will be received in the order " + "they were published."); Console.WriteLine(); var messageGroupId = GetUserResponse("Enter a message group ID for this message:", "1"); if (!_useContentBasedDeduplication) { Console.WriteLine("Because you are not using content-based deduplication, " + "you must enter a deduplication ID."); Console.WriteLine("Enter a deduplication ID for this message."); Publish messages to queues 433 Amazon Simple Queue Service Developer Guide deduplicationId = GetUserResponse("Enter a deduplication ID for this message.", "1"); } if (GetYesNoResponse("Add an attribute to this message?")) { Console.WriteLine("Enter a number for an attribute."); for (int i = 0; i < _tones.Length; i++) { Console.WriteLine($"\t{i + 1}. {_tones[i]}"); } var selection = GetUserResponse("", "1"); int.TryParse(selection, out var selectionNumber); if (selectionNumber > 0 && selectionNumber < _tones.Length) { toneAttribute = _tones[selectionNumber - 1]; } } var messageID = await SnsWrapper.PublishToTopicWithAttribute( _topicArn, message, "tone", toneAttribute, deduplicationId, messageGroupId); Console.WriteLine($"Message published with id {messageID}."); } keepSendingMessages = GetYesNoResponse("Send another message?", false); } } /// <summary> /// Poll for the published messages to see the results of the user's choices. /// </summary> /// <returns>Async task.</returns> public static async Task<List<Message>> PollForMessages(string queueUrl) { Console.WriteLine(new string('-', 80)); Console.WriteLine($"Now the SQS queue at {queueUrl} will be polled to retrieve the messages." + "\r\nPress any key to continue."); if (UseConsole) Publish messages to queues 434 Amazon Simple Queue Service { Console.ReadLine(); } var moreMessages = true; var messages = new List<Message>(); while (moreMessages) { Developer Guide var newMessages = await SqsWrapper.ReceiveMessagesByUrl(queueUrl, 10); moreMessages = newMessages.Any(); if (moreMessages) { messages.AddRange(newMessages); } } Console.WriteLine($"{messages.Count} message(s) were received by the queue at {queueUrl}."); foreach (var message in messages) { Console.WriteLine("\tMessage:" + $"\n\t{message.Body}"); } Console.WriteLine(new string('-', 80)); return messages; } /// <summary> /// Delete the message using handles in a batch. /// </summary> /// <returns>Async task.</returns> public static async Task DeleteMessages(string queueUrl, List<Message> messages) { Console.WriteLine(new string('-', 80)); Console.WriteLine("Now we can delete the messages in this queue in a batch."); await SqsWrapper.DeleteMessageBatchByUrl(queueUrl, messages); Console.WriteLine(new string('-', 80)); } Publish messages to queues 435 Amazon Simple Queue Service Developer Guide /// <summary> /// Clean up the resources from the scenario. /// </summary> /// <returns>Async task.</returns> private static async Task CleanupResources() { Console.WriteLine(new string('-', 80)); Console.WriteLine($"Clean up resources."); try { foreach (var queueUrl in _queueUrls) { if (!string.IsNullOrEmpty(queueUrl)) { var deleteQueue = GetYesNoResponse($"Delete queue with url {queueUrl}?"); if (deleteQueue) { await SqsWrapper.DeleteQueueByUrl(queueUrl); } } } foreach (var subscriptionArn in _subscriptionArns) { if (!string.IsNullOrEmpty(subscriptionArn)) { await SnsWrapper.UnsubscribeByArn(subscriptionArn); } } var deleteTopic = GetYesNoResponse($"Delete topic {_topicName}?"); if (deleteTopic) { await SnsWrapper.DeleteTopicByArn(_topicArn); } } catch (Exception ex) { Console.WriteLine($"Unable to clean up resources. Here's why: {ex.Message}."); } Publish messages to queues 436 Amazon Simple Queue Service Developer Guide Console.WriteLine(new string('-', 80)); } /// <summary> /// Helper method to get a yes or no response from the user. /// </summary> /// <param name="question">The question string to print on the console.</ param> /// <param name="defaultAnswer">Optional default answer to use.</param> /// <returns>True if the user responds with a yes.</returns> private static bool GetYesNoResponse(string question, bool defaultAnswer = true) { if (UseConsole) { Console.WriteLine(question); var ynResponse = Console.ReadLine(); var response = ynResponse != null && ynResponse.Equals("y", StringComparison.InvariantCultureIgnoreCase); return response; } // If not using the console, use the default. return defaultAnswer; } /// <summary> /// Helper method to get a string response from the user through the console. /// </summary> /// <param name="question">The question string to print on the console.</ param> /// <param name="defaultAnswer">Optional default answer to use.</param> /// <returns>True if the user responds with a yes.</returns> private static string GetUserResponse(string question, string defaultAnswer) { if (UseConsole) { var response = ""; while (string.IsNullOrEmpty(response)) { Console.WriteLine(question); response = Console.ReadLine(); } Publish messages to queues 437 Amazon Simple Queue Service Developer Guide return response; } // If not using the console, use the default. return defaultAnswer; } } Create a class that wraps Amazon SQS operations. /// <summary> /// Wrapper for Amazon Simple Queue Service (SQS) operations. /// </summary> public class SQSWrapper { private readonly IAmazonSQS _amazonSQSClient; /// <summary> /// Constructor for the Amazon SQS wrapper. /// </summary> /// <param name="amazonSQS">The injected Amazon SQS client.</param> public SQSWrapper(IAmazonSQS amazonSQS) { _amazonSQSClient = amazonSQS; } /// <summary> /// Create a queue with a specific name.
|
sqs-dg-116
|
sqs-dg.pdf
| 116 |
while (string.IsNullOrEmpty(response)) { Console.WriteLine(question); response = Console.ReadLine(); } Publish messages to queues 437 Amazon Simple Queue Service Developer Guide return response; } // If not using the console, use the default. return defaultAnswer; } } Create a class that wraps Amazon SQS operations. /// <summary> /// Wrapper for Amazon Simple Queue Service (SQS) operations. /// </summary> public class SQSWrapper { private readonly IAmazonSQS _amazonSQSClient; /// <summary> /// Constructor for the Amazon SQS wrapper. /// </summary> /// <param name="amazonSQS">The injected Amazon SQS client.</param> public SQSWrapper(IAmazonSQS amazonSQS) { _amazonSQSClient = amazonSQS; } /// <summary> /// Create a queue with a specific name. /// </summary> /// <param name="queueName">The name for the queue.</param> /// <param name="useFifoQueue">True to use a FIFO queue.</param> /// <returns>The url for the queue.</returns> public async Task<string> CreateQueueWithName(string queueName, bool useFifoQueue) { int maxMessage = 256 * 1024; var queueAttributes = new Dictionary<string, string> { { QueueAttributeName.MaximumMessageSize, maxMessage.ToString() } Publish messages to queues 438 Amazon Simple Queue Service }; Developer Guide var createQueueRequest = new CreateQueueRequest() { QueueName = queueName, Attributes = queueAttributes }; if (useFifoQueue) { // Update the name if it is not correct for a FIFO queue. if (!queueName.EndsWith(".fifo")) { createQueueRequest.QueueName = queueName + ".fifo"; } // Add an attribute for a FIFO queue. createQueueRequest.Attributes.Add( QueueAttributeName.FifoQueue, "true"); } var createResponse = await _amazonSQSClient.CreateQueueAsync( new CreateQueueRequest() { QueueName = queueName }); return createResponse.QueueUrl; } /// <summary> /// Get the ARN for a queue from its URL. /// </summary> /// <param name="queueUrl">The URL of the queue.</param> /// <returns>The ARN of the queue.</returns> public async Task<string> GetQueueArnByUrl(string queueUrl) { var getAttributesRequest = new GetQueueAttributesRequest() { QueueUrl = queueUrl, AttributeNames = new List<string>() { QueueAttributeName.QueueArn } }; var getAttributesResponse = await _amazonSQSClient.GetQueueAttributesAsync( Publish messages to queues 439 Amazon Simple Queue Service Developer Guide getAttributesRequest); return getAttributesResponse.QueueARN; } /// <summary> /// Set the policy attribute of a queue for a topic. /// </summary> /// <param name="queueArn">The ARN of the queue.</param> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="queueUrl">The url for the queue.</param> /// <returns>True if successful.</returns> public async Task<bool> SetQueuePolicyForTopic(string queueArn, string topicArn, string queueUrl) { var queuePolicy = "{" + "\"Version\": \"2012-10-17\"," + "\"Statement\": [{" + "\"Effect\": \"Allow\"," + "\"Principal\": {" + $"\"Service\": " + "\"sns.amazonaws.com\"" + "}," + "\"Action\": \"sqs:SendMessage\"," + $"\"Resource\": \"{queueArn}\"," + "\"Condition\": {" + "\"ArnEquals\": {" + $"\"aws:SourceArn\": \"{topicArn}\"" + "}" + "}" + "}]" + "}"; var attributesResponse = await _amazonSQSClient.SetQueueAttributesAsync( new SetQueueAttributesRequest() { QueueUrl = queueUrl, Attributes = new Dictionary<string, string>() { { "Policy", queuePolicy } } }); return attributesResponse.HttpStatusCode == HttpStatusCode.OK; } /// <summary> Publish messages to queues 440 Amazon Simple Queue Service Developer Guide /// Receive messages from a queue by its URL. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>The list of messages.</returns> public async Task<List<Message>> ReceiveMessagesByUrl(string queueUrl, int maxMessages) { // Setting WaitTimeSeconds to non-zero enables long polling. // For information about long polling, see // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/ SQSDeveloperGuide/sqs-short-and-long-polling.html var messageResponse = await _amazonSQSClient.ReceiveMessageAsync( new ReceiveMessageRequest() { QueueUrl = queueUrl, MaxNumberOfMessages = maxMessages, WaitTimeSeconds = 1 }); return messageResponse.Messages; } /// <summary> /// Delete a batch of messages from a queue by its url. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteMessageBatchByUrl(string queueUrl, List<Message> messages) { var deleteRequest = new DeleteMessageBatchRequest() { QueueUrl = queueUrl, Entries = new List<DeleteMessageBatchRequestEntry>() }; foreach (var message in messages) { deleteRequest.Entries.Add(new DeleteMessageBatchRequestEntry() { ReceiptHandle = message.ReceiptHandle, Id = message.MessageId }); } Publish messages to queues 441 Amazon Simple Queue Service Developer Guide var deleteResponse = await _amazonSQSClient.DeleteMessageBatchAsync(deleteRequest); return deleteResponse.Failed.Any(); } /// <summary> /// Delete a queue by its URL. /// </summary> /// <param name="queueUrl">The url of the queue.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteQueueByUrl(string queueUrl) { var deleteResponse = await _amazonSQSClient.DeleteQueueAsync( new DeleteQueueRequest() { QueueUrl = queueUrl }); return deleteResponse.HttpStatusCode == HttpStatusCode.OK; } } Create a class that wraps Amazon SNS operations. /// <summary> /// Wrapper for Amazon Simple Notification Service (SNS) operations. /// </summary> public class SNSWrapper { private readonly IAmazonSimpleNotificationService _amazonSNSClient; /// <summary> /// Constructor for the Amazon SNS wrapper. /// </summary> /// <param name="amazonSQS">The injected Amazon SNS client.</param> public SNSWrapper(IAmazonSimpleNotificationService amazonSNS) { _amazonSNSClient = amazonSNS; } /// <summary> Publish messages to queues 442 Amazon Simple Queue Service Developer Guide /// Create a new topic with a name and specific FIFO and de-duplication attributes. /// </summary> /// <param name="topicName">The name for the topic.</param> /// <param name="useFifoTopic">True to use a FIFO topic.</param> /// <param name="useContentBasedDeduplication">True to use content-based de- duplication.</param> /// <returns>The ARN of the new topic.</returns> public async Task<string> CreateTopicWithName(string topicName, bool useFifoTopic, bool useContentBasedDeduplication) { var createTopicRequest = new CreateTopicRequest() { Name = topicName, }; if (useFifoTopic) { // Update the name if it is not correct for a FIFO topic. if (!topicName.EndsWith(".fifo")) { createTopicRequest.Name = topicName + ".fifo"; } // Add the attributes from the method parameters.
|
sqs-dg-117
|
sqs-dg.pdf
| 117 |
Guide /// Create a new topic with a name and specific FIFO and de-duplication attributes. /// </summary> /// <param name="topicName">The name for the topic.</param> /// <param name="useFifoTopic">True to use a FIFO topic.</param> /// <param name="useContentBasedDeduplication">True to use content-based de- duplication.</param> /// <returns>The ARN of the new topic.</returns> public async Task<string> CreateTopicWithName(string topicName, bool useFifoTopic, bool useContentBasedDeduplication) { var createTopicRequest = new CreateTopicRequest() { Name = topicName, }; if (useFifoTopic) { // Update the name if it is not correct for a FIFO topic. if (!topicName.EndsWith(".fifo")) { createTopicRequest.Name = topicName + ".fifo"; } // Add the attributes from the method parameters. createTopicRequest.Attributes = new Dictionary<string, string> { { "FifoTopic", "true" } }; if (useContentBasedDeduplication) { createTopicRequest.Attributes.Add("ContentBasedDeduplication", "true"); } } var createResponse = await _amazonSNSClient.CreateTopicAsync(createTopicRequest); return createResponse.TopicArn; } /// <summary> /// Subscribe a queue to a topic with optional filters. /// </summary> Publish messages to queues 443 Amazon Simple Queue Service Developer Guide /// <param name="topicArn">The ARN of the topic.</param> /// <param name="useFifoTopic">The optional filtering policy for the subscription.</param> /// <param name="queueArn">The ARN of the queue.</param> /// <returns>The ARN of the new subscription.</returns> public async Task<string> SubscribeTopicWithFilter(string topicArn, string? filterPolicy, string queueArn) { var subscribeRequest = new SubscribeRequest() { TopicArn = topicArn, Protocol = "sqs", Endpoint = queueArn }; if (!string.IsNullOrEmpty(filterPolicy)) { subscribeRequest.Attributes = new Dictionary<string, string> { { "FilterPolicy", filterPolicy } }; } var subscribeResponse = await _amazonSNSClient.SubscribeAsync(subscribeRequest); return subscribeResponse.SubscriptionArn; } /// <summary> /// Publish a message to a topic with an attribute and optional deduplication and group IDs. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <param name="message">The message to publish.</param> /// <param name="attributeName">The optional attribute for the message.</ param> /// <param name="attributeValue">The optional attribute value for the message.</param> /// <param name="deduplicationId">The optional deduplication ID for the message.</param> /// <param name="groupId">The optional group ID for the message.</param> /// <returns>The ID of the message published.</returns> public async Task<string> PublishToTopicWithAttribute( string topicArn, string message, string? attributeName = null, Publish messages to queues 444 Amazon Simple Queue Service Developer Guide string? attributeValue = null, string? deduplicationId = null, string? groupId = null) { var publishRequest = new PublishRequest() { TopicArn = topicArn, Message = message, MessageDeduplicationId = deduplicationId, MessageGroupId = groupId }; if (attributeValue != null) { // Add the string attribute if it exists. publishRequest.MessageAttributes = new Dictionary<string, MessageAttributeValue> { { attributeName!, new MessageAttributeValue() { StringValue = attributeValue, DataType = "String"} } }; } var publishResponse = await _amazonSNSClient.PublishAsync(publishRequest); return publishResponse.MessageId; } /// <summary> /// Unsubscribe from a topic by a subscription ARN. /// </summary> /// <param name="subscriptionArn">The ARN of the subscription.</param> /// <returns>True if successful.</returns> public async Task<bool> UnsubscribeByArn(string subscriptionArn) { var unsubscribeResponse = await _amazonSNSClient.UnsubscribeAsync( new UnsubscribeRequest() { SubscriptionArn = subscriptionArn }); return unsubscribeResponse.HttpStatusCode == HttpStatusCode.OK; } Publish messages to queues 445 Amazon Simple Queue Service Developer Guide /// <summary> /// Delete a topic by its topic ARN. /// </summary> /// <param name="topicArn">The ARN of the topic.</param> /// <returns>True if successful.</returns> public async Task<bool> DeleteTopicByArn(string topicArn) { var deleteResponse = await _amazonSNSClient.DeleteTopicAsync( new DeleteTopicRequest() { TopicArn = topicArn }); return deleteResponse.HttpStatusCode == HttpStatusCode.OK; } } • For API details, see the following topics in AWS SDK for .NET API Reference. • CreateQueue • CreateTopic • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe Publish messages to queues 446 Amazon Simple Queue Service C++ SDK for C++ Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; //! Workflow for messaging with topics and queues using Amazon SNS and Amazon SQS. /*! \param clientConfig Aws client configuration. \return bool: Successful completion. */ bool AwsDoc::TopicsAndQueues::messagingWithTopicsAndQueues( const Aws::Client::ClientConfiguration &clientConfiguration) { std::cout << "Welcome to messaging with topics and queues." << std::endl; printAsterisksLine(); std::cout << "In this workflow, you will create an SNS topic and subscribe " << NUMBER_OF_QUEUES << " SQS queues to the topic." << std::endl; std::cout << "You can select from several options for configuring the topic and the subscriptions for the " << NUMBER_OF_QUEUES << " queues." << std::endl; std::cout << "You can then post to the topic and see the results in the queues." << std::endl; Aws::SNS::SNSClient snsClient(clientConfiguration); printAsterisksLine(); std::cout << "SNS topics can be configured as FIFO (First-In-First-Out)." << std::endl; std::cout Publish messages to queues 447 Amazon Simple Queue Service Developer Guide << "FIFO topics deliver messages in order and support deduplication and message filtering." << std::endl; bool isFifoTopic = askYesNoQuestion( "Would you like to work with FIFO topics? (y/n) "); bool contentBasedDeduplication = false; Aws::String topicName; if (isFifoTopic) { printAsterisksLine(); std::cout << "Because you have chosen a FIFO topic, deduplication is supported." << std::endl; std::cout << "Deduplication IDs are either set in the message or
|
sqs-dg-118
|
sqs-dg.pdf
| 118 |
and see the results in the queues." << std::endl; Aws::SNS::SNSClient snsClient(clientConfiguration); printAsterisksLine(); std::cout << "SNS topics can be configured as FIFO (First-In-First-Out)." << std::endl; std::cout Publish messages to queues 447 Amazon Simple Queue Service Developer Guide << "FIFO topics deliver messages in order and support deduplication and message filtering." << std::endl; bool isFifoTopic = askYesNoQuestion( "Would you like to work with FIFO topics? (y/n) "); bool contentBasedDeduplication = false; Aws::String topicName; if (isFifoTopic) { printAsterisksLine(); std::cout << "Because you have chosen a FIFO topic, deduplication is supported." << std::endl; std::cout << "Deduplication IDs are either set in the message or automatically generated " << "from content using a hash function." << std::endl; std::cout << "If a message is successfully published to an SNS FIFO topic, any message " << "published and determined to have the same deduplication ID, " << std::endl; std::cout << "within the five-minute deduplication interval, is accepted but not delivered." << std::endl; std::cout << "For more information about deduplication, " << "see https://docs.aws.amazon.com/sns/latest/dg/fifo-message- dedup.html." << std::endl; contentBasedDeduplication = askYesNoQuestion( "Use content-based deduplication instead of entering a deduplication ID? (y/n) "); } printAsterisksLine(); Aws::SQS::SQSClient sqsClient(clientConfiguration); Aws::Vector<Aws::String> queueURLS; Aws::Vector<Aws::String> subscriptionARNS; Aws::String topicARN; { Publish messages to queues 448 Amazon Simple Queue Service Developer Guide topicName = askQuestion("Enter a name for your SNS topic. "); // 1. Create an Amazon SNS topic, either FIFO or non-FIFO. Aws::SNS::Model::CreateTopicRequest request; if (isFifoTopic) { request.AddAttributes("FifoTopic", "true"); if (contentBasedDeduplication) { request.AddAttributes("ContentBasedDeduplication", "true"); } topicName = topicName + FIFO_SUFFIX; std::cout << "Because you have selected a FIFO topic, '.fifo' must be appended to the topic name." << std::endl; } request.SetName(topicName); Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request); if (outcome.IsSuccess()) { topicARN = outcome.GetResult().GetTopicArn(); std::cout << "Your new topic with the name '" << topicName << "' and the topic Amazon Resource Name (ARN) " << std::endl; std::cout << "'" << topicARN << "' has been created." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::CreateTopic. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } Publish messages to queues 449 Amazon Simple Queue Service } printAsterisksLine(); Developer Guide std::cout << "Now you will create " << NUMBER_OF_QUEUES << " SQS queues to subscribe to the topic." << std::endl; Aws::Vector<Aws::String> queueNames; bool filteringMessages = false; bool first = true; for (int i = 1; i <= NUMBER_OF_QUEUES; ++i) { Aws::String queueURL; Aws::String queueName; { printAsterisksLine(); std::ostringstream ostringstream; ostringstream << "Enter a name for " << (first ? "an" : "the next") << " SQS queue. "; queueName = askQuestion(ostringstream.str()); // 2. Create an SQS queue. Aws::SQS::Model::CreateQueueRequest request; if (isFifoTopic) { request.AddAttributes(Aws::SQS::Model::QueueAttributeName::FifoQueue, "true"); queueName = queueName + FIFO_SUFFIX; if (first) // Only explain this once. { std::cout << "Because you are creating a FIFO SQS queue, '.fifo' must " << "be appended to the queue name." << std::endl; } } request.SetQueueName(queueName); queueNames.push_back(queueName); Aws::SQS::Model::CreateQueueOutcome outcome = sqsClient.CreateQueue(request); if (outcome.IsSuccess()) { queueURL = outcome.GetResult().GetQueueUrl(); Publish messages to queues 450 Amazon Simple Queue Service Developer Guide std::cout << "Your new SQS queue with the name '" << queueName << "' and the queue URL " << std::endl; std::cout << "'" << queueURL << "' has been created." << std::endl; } else { std::cerr << "Error with SQS::CreateQueue. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } queueURLS.push_back(queueURL); if (first) // Only explain this once. { std::cout << "The queue URL is used to retrieve the queue ARN, which is " << "used to create a subscription." << std::endl; } Aws::String queueARN; { // 3. Get the SQS queue ARN attribute. Aws::SQS::Model::GetQueueAttributesRequest request; request.SetQueueUrl(queueURL); request.AddAttributeNames(Aws::SQS::Model::QueueAttributeName::QueueArn); Aws::SQS::Model::GetQueueAttributesOutcome outcome = sqsClient.GetQueueAttributes(request); if (outcome.IsSuccess()) { const Aws::Map<Aws::SQS::Model::QueueAttributeName, Aws::String> &attributes = outcome.GetResult().GetAttributes(); Publish messages to queues 451 Amazon Simple Queue Service Developer Guide const auto &iter = attributes.find( Aws::SQS::Model::QueueAttributeName::QueueArn); if (iter != attributes.end()) { queueARN = iter->second; std::cout << "The queue ARN '" << queueARN << "' has been retrieved." << std::endl; } else { std::cerr << "Error ARN attribute not returned by GetQueueAttribute." << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } else { std::cerr << "Error with SQS::GetQueueAttributes. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } if (first) { std::cout << "An IAM policy must be attached to an SQS queue, enabling it to receive " "messages from an SNS topic." << std::endl; } Publish messages to queues 452 Amazon Simple Queue Service Developer Guide { // 4. Set the SQS queue policy attribute with a policy enabling the receipt of SNS messages. Aws::SQS::Model::SetQueueAttributesRequest request; request.SetQueueUrl(queueURL); Aws::String policy = createPolicyForQueue(queueARN, topicARN); request.AddAttributes(Aws::SQS::Model::QueueAttributeName::Policy, policy); Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes(request); if (outcome.IsSuccess()) { std::cout << "The attributes for the queue '" << queueName << "' were successfully updated." << std::endl; } else { std::cerr << "Error with SQS::SetQueueAttributes. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } }
|
sqs-dg-119
|
sqs-dg.pdf
| 119 |
SQS queue, enabling it to receive " "messages from an SNS topic." << std::endl; } Publish messages to queues 452 Amazon Simple Queue Service Developer Guide { // 4. Set the SQS queue policy attribute with a policy enabling the receipt of SNS messages. Aws::SQS::Model::SetQueueAttributesRequest request; request.SetQueueUrl(queueURL); Aws::String policy = createPolicyForQueue(queueARN, topicARN); request.AddAttributes(Aws::SQS::Model::QueueAttributeName::Policy, policy); Aws::SQS::Model::SetQueueAttributesOutcome outcome = sqsClient.SetQueueAttributes(request); if (outcome.IsSuccess()) { std::cout << "The attributes for the queue '" << queueName << "' were successfully updated." << std::endl; } else { std::cerr << "Error with SQS::SetQueueAttributes. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } printAsterisksLine(); { // 5. Subscribe the SQS queue to the SNS topic. Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("sqs"); request.SetEndpoint(queueARN); if (isFifoTopic) { if (first) { std::cout << "Subscriptions to a FIFO topic can have filters." Publish messages to queues 453 Amazon Simple Queue Service Developer Guide << std::endl; std::cout << "If you add a filter to this subscription, then only the filtered messages " << "will be received in the queue." << std::endl; std::cout << "For information about message filtering, " << "see https://docs.aws.amazon.com/sns/latest/dg/ sns-message-filtering.html" << std::endl; std::cout << "For this example, you can filter messages by a \"" << TONE_ATTRIBUTE << "\" attribute." << std::endl; } std::ostringstream ostringstream; ostringstream << "Filter messages for \"" << queueName << "\"'s subscription to the topic \"" << topicName << "\"? (y/n)"; // Add filter if user answers yes. if (askYesNoQuestion(ostringstream.str())) { Aws::String jsonPolicy = getFilterPolicyFromUser(); if (!jsonPolicy.empty()) { filteringMessages = true; std::cout << "This is the filter policy for this subscription." << std::endl; std::cout << jsonPolicy << std::endl; request.AddAttributes("FilterPolicy", jsonPolicy); } else { std::cout << "Because you did not select any attributes, no filter " << "will be added to this subscription." << std::endl; } } } // if (isFifoTopic) Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); Publish messages to queues 454 Amazon Simple Queue Service Developer Guide if (outcome.IsSuccess()) { Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn(); std::cout << "The queue '" << queueName << "' has been subscribed to the topic '" << "'" << topicName << "'" << std::endl; std::cout << "with the subscription ARN '" << subscriptionARN << "." << std::endl; subscriptionARNS.push_back(subscriptionARN); } else { std::cerr << "Error with TopicsAndQueues::Subscribe. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } first = false; } first = true; do { printAsterisksLine(); // 6. Publish a message to the SNS topic. Aws::SNS::Model::PublishRequest request; request.SetTopicArn(topicARN); Aws::String message = askQuestion("Enter a message text to publish. "); request.SetMessage(message); if (isFifoTopic) { if (first) { std::cout << "Because you are using a FIFO topic, you must set a message group ID." << std::endl; Publish messages to queues 455 Amazon Simple Queue Service Developer Guide std::cout << "All messages within the same group will be received in the " << "order they were published." << std::endl; } Aws::String messageGroupID = askQuestion( "Enter a message group ID for this message. "); request.SetMessageGroupId(messageGroupID); if (!contentBasedDeduplication) { if (first) { std::cout << "Because you are not using content-based deduplication, " << "you must enter a deduplication ID." << std::endl; } Aws::String deduplicationID = askQuestion( "Enter a deduplication ID for this message. "); request.SetMessageDeduplicationId(deduplicationID); } } if (filteringMessages && askYesNoQuestion( "Add an attribute to this message? (y/n) ")) { for (size_t i = 0; i < TONES.size(); ++i) { std::cout << " " << (i + 1) << ". " << TONES[i] << std::endl; } int selection = askQuestionForIntRange( "Enter a number for an attribute. ", 1, static_cast<int>(TONES.size())); Aws::SNS::Model::MessageAttributeValue messageAttributeValue; messageAttributeValue.SetDataType("String"); messageAttributeValue.SetStringValue(TONES[selection - 1]); request.AddMessageAttributes(TONE_ATTRIBUTE, messageAttributeValue); } Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request); if (outcome.IsSuccess()) { std::cout << "Your message was successfully published." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::Publish. " << outcome.GetError().GetMessage() << std::endl; Publish messages to queues 456 Amazon Simple Queue Service Developer Guide cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } first = false; } while (askYesNoQuestion("Post another message? (y/n) ")); printAsterisksLine(); std::cout << "Now the SQS queue will be polled to retrieve the messages." << std::endl; askQuestion("Press any key to continue...", alwaysTrueTest); for (size_t i = 0; i < queueURLS.size(); ++i) { // 7. Poll an SQS queue for its messages. std::vector<Aws::String> messages; std::vector<Aws::String> receiptHandles; while (true) { Aws::SQS::Model::ReceiveMessageRequest request; request.SetMaxNumberOfMessages(10); request.SetQueueUrl(queueURLS[i]); // Setting WaitTimeSeconds to non-zero enables long polling. // For information about long polling, see // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/ SQSDeveloperGuide/sqs-short-and-long-polling.html request.SetWaitTimeSeconds(1); Aws::SQS::Model::ReceiveMessageOutcome outcome = sqsClient.ReceiveMessage(request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::SQS::Model::Message> &newMessages = outcome.GetResult().GetMessages(); if (newMessages.empty()) { break; } else { for (const Aws::SQS::Model::Message &message: newMessages) { Publish messages to queues 457 Amazon Simple Queue Service Developer Guide messages.push_back(message.GetBody()); receiptHandles.push_back(message.GetReceiptHandle()); } } } else { std::cerr << "Error with SQS::ReceiveMessage. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } printAsterisksLine(); if (messages.empty()) { std::cout << "No messages were "; } else if (messages.size() == 1) { std::cout << "One message was "; } else
|
sqs-dg-120
|
sqs-dg.pdf
| 120 |
long polling. // For information about long polling, see // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/ SQSDeveloperGuide/sqs-short-and-long-polling.html request.SetWaitTimeSeconds(1); Aws::SQS::Model::ReceiveMessageOutcome outcome = sqsClient.ReceiveMessage(request); if (outcome.IsSuccess()) { const Aws::Vector<Aws::SQS::Model::Message> &newMessages = outcome.GetResult().GetMessages(); if (newMessages.empty()) { break; } else { for (const Aws::SQS::Model::Message &message: newMessages) { Publish messages to queues 457 Amazon Simple Queue Service Developer Guide messages.push_back(message.GetBody()); receiptHandles.push_back(message.GetReceiptHandle()); } } } else { std::cerr << "Error with SQS::ReceiveMessage. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } printAsterisksLine(); if (messages.empty()) { std::cout << "No messages were "; } else if (messages.size() == 1) { std::cout << "One message was "; } else { std::cout << messages.size() << " messages were "; } std::cout << "received by the queue '" << queueNames[i] << "'." << std::endl; for (const Aws::String &message: messages) { std::cout << " Message : '" << message << "'." << std::endl; } // 8. Delete a batch of messages from an SQS queue. if (!receiptHandles.empty()) { Aws::SQS::Model::DeleteMessageBatchRequest request; request.SetQueueUrl(queueURLS[i]); int id = 1; // Ids must be unique within a batch delete request. for (const Aws::String &receiptHandle: receiptHandles) { Publish messages to queues 458 Amazon Simple Queue Service Developer Guide Aws::SQS::Model::DeleteMessageBatchRequestEntry entry; entry.SetId(std::to_string(id)); ++id; entry.SetReceiptHandle(receiptHandle); request.AddEntries(entry); } Aws::SQS::Model::DeleteMessageBatchOutcome outcome = sqsClient.DeleteMessageBatch(request); if (outcome.IsSuccess()) { std::cout << "The batch deletion of messages was successful." << std::endl; } else { std::cerr << "Error with SQS::DeleteMessageBatch. " << outcome.GetError().GetMessage() << std::endl; cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient); return false; } } } return cleanUp(topicARN, queueURLS, subscriptionARNS, snsClient, sqsClient, true); // askUser } bool AwsDoc::TopicsAndQueues::cleanUp(const Aws::String &topicARN, const Aws::Vector<Aws::String> &queueURLS, const Aws::Vector<Aws::String> &subscriptionARNS, const Aws::SNS::SNSClient &snsClient, const Aws::SQS::SQSClient &sqsClient, Publish messages to queues 459 Amazon Simple Queue Service Developer Guide bool askUser) { bool result = true; printAsterisksLine(); if (!queueURLS.empty() && askUser && askYesNoQuestion("Delete the SQS queues? (y/n) ")) { for (const auto &queueURL: queueURLS) { // 9. Delete an SQS queue. Aws::SQS::Model::DeleteQueueRequest request; request.SetQueueUrl(queueURL); Aws::SQS::Model::DeleteQueueOutcome outcome = sqsClient.DeleteQueue(request); if (outcome.IsSuccess()) { std::cout << "The queue with URL '" << queueURL << "' was successfully deleted." << std::endl; } else { std::cerr << "Error with SQS::DeleteQueue. " << outcome.GetError().GetMessage() << std::endl; result = false; } } for (const auto &subscriptionARN: subscriptionARNS) { // 10. Unsubscribe an SNS subscription. Aws::SNS::Model::UnsubscribeRequest request; request.SetSubscriptionArn(subscriptionARN); Aws::SNS::Model::UnsubscribeOutcome outcome = snsClient.Unsubscribe(request); if (outcome.IsSuccess()) { std::cout << "Unsubscribe of subscription ARN '" << subscriptionARN << "' was successful." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::Unsubscribe. " << outcome.GetError().GetMessage() << std::endl; result = false; Publish messages to queues 460 Amazon Simple Queue Service Developer Guide } } } printAsterisksLine(); if (!topicARN.empty() && askUser && askYesNoQuestion("Delete the SNS topic? (y/n) ")) { // 11. Delete an SNS topic. Aws::SNS::Model::DeleteTopicRequest request; request.SetTopicArn(topicARN); Aws::SNS::Model::DeleteTopicOutcome outcome = snsClient.DeleteTopic(request); if (outcome.IsSuccess()) { std::cout << "The topic with ARN '" << topicARN << "' was successfully deleted." << std::endl; } else { std::cerr << "Error with TopicsAndQueues::DeleteTopicRequest. " << outcome.GetError().GetMessage() << std::endl; result = false; } } return result; } //! Create an IAM policy that gives an SQS queue permission to receive messages from an SNS topic. /*! \sa createPolicyForQueue() \param queueARN: The SQS queue Amazon Resource Name (ARN). \param topicARN: The SNS topic ARN. \return Aws::String: The policy as JSON. */ Aws::String AwsDoc::TopicsAndQueues::createPolicyForQueue(const Aws::String &queueARN, const Aws::String &topicARN) { std::ostringstream policyStream; policyStream << R"({ Publish messages to queues 461 Amazon Simple Queue Service Developer Guide "Statement": [ { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": ")" << queueARN << R"(", "Condition": { "ArnEquals": { "aws:SourceArn": ")" << topicARN << R"(" } } } ] })"; return policyStream.str(); } • For API details, see the following topics in AWS SDK for C++ API Reference. • CreateQueue • CreateTopic • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe Publish messages to queues 462 Amazon Simple Queue Service Go SDK for Go V2 Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Run an interactive scenario at a command prompt. import ( "context" "encoding/json" "fmt" "log" "strings" "topics_and_queues/actions" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" "github.com/awsdocs/aws-doc-sdk-examples/gov2/demotools" ) const FIFO_SUFFIX = ".fifo" const TONE_KEY = "tone" var ToneChoices = []string{"cheerful", "funny", "serious", "sincere"} // MessageBody is used to deserialize the body of a message from a JSON string. type MessageBody struct { Message string } // ScenarioRunner separates the steps of this scenario into individual functions so that // they are simpler to read and understand. type ScenarioRunner struct { questioner demotools.IQuestioner Publish messages to queues 463 Amazon Simple Queue Service Developer Guide snsActor *actions.SnsActions sqsActor *actions.SqsActions } func (runner ScenarioRunner) CreateTopic(ctx context.Context) (string, string, bool, bool) { log.Println("SNS topics can be configured as FIFO (First-In-First-Out) or standard.\n" + "FIFO topics deliver messages in order and support deduplication and message filtering.") isFifoTopic :=
|
sqs-dg-121
|
sqs-dg.pdf
| 121 |
// MessageBody is used to deserialize the body of a message from a JSON string. type MessageBody struct { Message string } // ScenarioRunner separates the steps of this scenario into individual functions so that // they are simpler to read and understand. type ScenarioRunner struct { questioner demotools.IQuestioner Publish messages to queues 463 Amazon Simple Queue Service Developer Guide snsActor *actions.SnsActions sqsActor *actions.SqsActions } func (runner ScenarioRunner) CreateTopic(ctx context.Context) (string, string, bool, bool) { log.Println("SNS topics can be configured as FIFO (First-In-First-Out) or standard.\n" + "FIFO topics deliver messages in order and support deduplication and message filtering.") isFifoTopic := runner.questioner.AskBool("\nWould you like to work with FIFO topics? (y/n) ", "y") contentBasedDeduplication := false if isFifoTopic { log.Println(strings.Repeat("-", 88)) log.Println("Because you have chosen a FIFO topic, deduplication is supported. \n" + "Deduplication IDs are either set in the message or are automatically generated\n" + "from content using a hash function. If a message is successfully published to \n" + "an SNS FIFO topic, any message published and determined to have the same\n" + "deduplication ID, within the five-minute deduplication interval, is accepted \n" + "but not delivered. For more information about deduplication, see:\n" + "\thttps://docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html.") contentBasedDeduplication = runner.questioner.AskBool( "\nDo you want to use content-based deduplication instead of entering a deduplication ID? (y/n) ", "y") } log.Println(strings.Repeat("-", 88)) topicName := runner.questioner.Ask("Enter a name for your SNS topic. ") if isFifoTopic { topicName = fmt.Sprintf("%v%v", topicName, FIFO_SUFFIX) log.Printf("Because you have selected a FIFO topic, '%v' must be appended to \n"+ "the topic name.", FIFO_SUFFIX) } topicArn, err := runner.snsActor.CreateTopic(ctx, topicName, isFifoTopic, contentBasedDeduplication) if err != nil { Publish messages to queues 464 Amazon Simple Queue Service panic(err) Developer Guide } log.Printf("Your new topic with the name '%v' and Amazon Resource Name (ARN) \n"+ "'%v' has been created.", topicName, topicArn) return topicName, topicArn, isFifoTopic, contentBasedDeduplication } func (runner ScenarioRunner) CreateQueue(ctx context.Context, ordinal string, isFifoTopic bool) (string, string) { queueName := runner.questioner.Ask(fmt.Sprintf("Enter a name for the %v SQS queue. ", ordinal)) if isFifoTopic { queueName = fmt.Sprintf("%v%v", queueName, FIFO_SUFFIX) if ordinal == "first" { log.Printf("Because you are creating a FIFO SQS queue, '%v' must "+ "be appended to the queue name.\n", FIFO_SUFFIX) } } queueUrl, err := runner.sqsActor.CreateQueue(ctx, queueName, isFifoTopic) if err != nil { panic(err) } log.Printf("Your new SQS queue with the name '%v' and the queue URL "+ "'%v' has been created.", queueName, queueUrl) return queueName, queueUrl } func (runner ScenarioRunner) SubscribeQueueToTopic( ctx context.Context, queueName string, queueUrl string, topicName string, topicArn string, ordinal string, isFifoTopic bool) (string, bool) { queueArn, err := runner.sqsActor.GetQueueArn(ctx, queueUrl) if err != nil { panic(err) } log.Printf("The ARN of your queue is: %v.\n", queueArn) err = runner.sqsActor.AttachSendMessagePolicy(ctx, queueUrl, queueArn, topicArn) if err != nil { panic(err) Publish messages to queues 465 Amazon Simple Queue Service } Developer Guide log.Println("Attached an IAM policy to the queue so the SNS topic can send " + "messages to it.") log.Println(strings.Repeat("-", 88)) var filterPolicy map[string][]string if isFifoTopic { if ordinal == "first" { log.Println("Subscriptions to a FIFO topic can have filters.\n" + "If you add a filter to this subscription, then only the filtered messages\n" + "will be received in the queue.\n" + "For information about message filtering, see\n" + "\thttps://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html\n" + "For this example, you can filter messages by a \"tone\" attribute.") } wantFiltering := runner.questioner.AskBool( fmt.Sprintf("Do you want to filter messages that are sent to \"%v\"\n"+ "from the %v topic? (y/n) ", queueName, topicName), "y") if wantFiltering { log.Println("You can filter messages by one or more of the following \"tone\" attributes.") var toneSelections []string askAboutTones := true for askAboutTones { toneIndex := runner.questioner.AskChoice( "Enter the number of the tone you want to filter by:\n", ToneChoices) toneSelections = append(toneSelections, ToneChoices[toneIndex]) askAboutTones = runner.questioner.AskBool("Do you want to add another tone to the filter? (y/n) ", "y") } log.Printf("Your subscription will be filtered to only pass the following tones: %v\n", toneSelections) filterPolicy = map[string][]string{TONE_KEY: toneSelections} } } subscriptionArn, err := runner.snsActor.SubscribeQueue(ctx, topicArn, queueArn, filterPolicy) if err != nil { panic(err) } Publish messages to queues 466 Amazon Simple Queue Service Developer Guide log.Printf("The queue %v is now subscribed to the topic %v with the subscription ARN %v.\n", queueName, topicName, subscriptionArn) return subscriptionArn, filterPolicy != nil } func (runner ScenarioRunner) PublishMessages(ctx context.Context, topicArn string, isFifoTopic bool, contentBasedDeduplication bool, usingFilters bool) { var message string var groupId string var dedupId string var toneSelection string publishMore := true for publishMore { groupId = "" dedupId = "" toneSelection = "" message = runner.questioner.Ask("Enter a message to publish: ") if isFifoTopic { log.Println("Because you are using a FIFO topic, you must set a message group ID.\n" + "All messages within the same group will be received in the order they were published.") groupId = runner.questioner.Ask("Enter a message group ID: ") if !contentBasedDeduplication { log.Println("Because you are not using content-based deduplication,\n" + "you must enter a deduplication
|
sqs-dg-122
|
sqs-dg.pdf
| 122 |
string, isFifoTopic bool, contentBasedDeduplication bool, usingFilters bool) { var message string var groupId string var dedupId string var toneSelection string publishMore := true for publishMore { groupId = "" dedupId = "" toneSelection = "" message = runner.questioner.Ask("Enter a message to publish: ") if isFifoTopic { log.Println("Because you are using a FIFO topic, you must set a message group ID.\n" + "All messages within the same group will be received in the order they were published.") groupId = runner.questioner.Ask("Enter a message group ID: ") if !contentBasedDeduplication { log.Println("Because you are not using content-based deduplication,\n" + "you must enter a deduplication ID.") dedupId = runner.questioner.Ask("Enter a deduplication ID: ") } } if usingFilters { if runner.questioner.AskBool("Add a tone attribute so this message can be filtered? (y/n) ", "y") { toneIndex := runner.questioner.AskChoice( "Enter the number of the tone you want to filter by:\n", ToneChoices) toneSelection = ToneChoices[toneIndex] } } err := runner.snsActor.Publish(ctx, topicArn, message, groupId, dedupId, TONE_KEY, toneSelection) if err != nil { panic(err) Publish messages to queues 467 Amazon Simple Queue Service } log.Println(("Your message was published.")) Developer Guide publishMore = runner.questioner.AskBool("Do you want to publish another messsage? (y/n) ", "y") } } func (runner ScenarioRunner) PollForMessages(ctx context.Context, queueUrls []string) { log.Println("Polling queues for messages...") for _, queueUrl := range queueUrls { var messages []types.Message for { currentMsgs, err := runner.sqsActor.GetMessages(ctx, queueUrl, 10, 1) if err != nil { panic(err) } if len(currentMsgs) == 0 { break } messages = append(messages, currentMsgs...) } if len(messages) == 0 { log.Printf("No messages were received by queue %v.\n", queueUrl) } else if len(messages) == 1 { log.Printf("One message was received by queue %v:\n", queueUrl) } else { log.Printf("%v messages were received by queue %v:\n", len(messages), queueUrl) } for msgIndex, message := range messages { messageBody := MessageBody{} err := json.Unmarshal([]byte(*message.Body), &messageBody) if err != nil { panic(err) } log.Printf("Message %v: %v\n", msgIndex+1, messageBody.Message) } if len(messages) > 0 { log.Printf("Deleting %v messages from queue %v.\n", len(messages), queueUrl) err := runner.sqsActor.DeleteMessages(ctx, queueUrl, messages) Publish messages to queues 468 Amazon Simple Queue Service Developer Guide if err != nil { panic(err) } } } } // RunTopicsAndQueuesScenario is an interactive example that shows you how to use the // AWS SDK for Go to create and use Amazon SNS topics and Amazon SQS queues. // // 1. Create a topic (FIFO or non-FIFO). // 2. Subscribe several queues to the topic with an option to apply a filter. // 3. Publish messages to the topic. // 4. Poll the queues for messages received. // 5. Delete the topic and the queues. // // This example creates service clients from the specified sdkConfig so that // you can replace it with a mocked or stubbed config for unit testing. // // It uses a questioner from the `demotools` package to get input during the example. // This package can be found in the ..\..\demotools folder of this repo. func RunTopicsAndQueuesScenario( ctx context.Context, sdkConfig aws.Config, questioner demotools.IQuestioner) { resources := Resources{} defer func() { if r := recover(); r != nil { log.Println("Something went wrong with the demo.\n" + "Cleaning up any resources that were created...") resources.Cleanup(ctx) } }() queueCount := 2 log.Println(strings.Repeat("-", 88)) log.Printf("Welcome to messaging with topics and queues.\n\n"+ "In this scenario, you will create an SNS topic and subscribe %v SQS queues to the\n"+ "topic. You can select from several options for configuring the topic and the \n"+ "subscriptions for the queues. You can then post to the topic and see the results\n"+ "in the queues.\n", queueCount) Publish messages to queues 469 Amazon Simple Queue Service Developer Guide log.Println(strings.Repeat("-", 88)) runner := ScenarioRunner{ questioner: questioner, snsActor: &actions.SnsActions{SnsClient: sns.NewFromConfig(sdkConfig)}, sqsActor: &actions.SqsActions{SqsClient: sqs.NewFromConfig(sdkConfig)}, } resources.snsActor = runner.snsActor resources.sqsActor = runner.sqsActor topicName, topicArn, isFifoTopic, contentBasedDeduplication := runner.CreateTopic(ctx) resources.topicArn = topicArn log.Println(strings.Repeat("-", 88)) log.Printf("Now you will create %v SQS queues and subscribe them to the topic. \n", queueCount) ordinals := []string{"first", "next"} usingFilters := false for _, ordinal := range ordinals { queueName, queueUrl := runner.CreateQueue(ctx, ordinal, isFifoTopic) resources.queueUrls = append(resources.queueUrls, queueUrl) _, filtering := runner.SubscribeQueueToTopic(ctx, queueName, queueUrl, topicName, topicArn, ordinal, isFifoTopic) usingFilters = usingFilters || filtering } log.Println(strings.Repeat("-", 88)) runner.PublishMessages(ctx, topicArn, isFifoTopic, contentBasedDeduplication, usingFilters) log.Println(strings.Repeat("-", 88)) runner.PollForMessages(ctx, resources.queueUrls) log.Println(strings.Repeat("-", 88)) wantCleanup := questioner.AskBool("Do you want to remove all AWS resources created for this scenario? (y/n) ", "y") if wantCleanup { log.Println("Cleaning up resources...") resources.Cleanup(ctx) } Publish messages to queues 470 Amazon Simple Queue Service Developer Guide log.Println(strings.Repeat("-", 88)) log.Println("Thanks for watching!") log.Println(strings.Repeat("-", 88)) } Define a struct that wraps Amazon SNS actions used in this example. import ( "context" "encoding/json" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // CreateTopic creates an Amazon SNS topic with the specified name. You can optionally // specify that the topic
|
sqs-dg-123
|
sqs-dg.pdf
| 123 |
all AWS resources created for this scenario? (y/n) ", "y") if wantCleanup { log.Println("Cleaning up resources...") resources.Cleanup(ctx) } Publish messages to queues 470 Amazon Simple Queue Service Developer Guide log.Println(strings.Repeat("-", 88)) log.Println("Thanks for watching!") log.Println(strings.Repeat("-", 88)) } Define a struct that wraps Amazon SNS actions used in this example. import ( "context" "encoding/json" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sns" "github.com/aws/aws-sdk-go-v2/service/sns/types" ) // SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions // used in the examples. type SnsActions struct { SnsClient *sns.Client } // CreateTopic creates an Amazon SNS topic with the specified name. You can optionally // specify that the topic is created as a FIFO topic and whether it uses content- based // deduplication instead of ID-based deduplication. func (actor SnsActions) CreateTopic(ctx context.Context, topicName string, isFifoTopic bool, contentBasedDeduplication bool) (string, error) { var topicArn string topicAttributes := map[string]string{} if isFifoTopic { topicAttributes["FifoTopic"] = "true" } if contentBasedDeduplication { topicAttributes["ContentBasedDeduplication"] = "true" Publish messages to queues 471 Amazon Simple Queue Service } Developer Guide topic, err := actor.SnsClient.CreateTopic(ctx, &sns.CreateTopicInput{ Name: aws.String(topicName), Attributes: topicAttributes, }) if err != nil { log.Printf("Couldn't create topic %v. Here's why: %v\n", topicName, err) } else { topicArn = *topic.TopicArn } return topicArn, err } // DeleteTopic delete an Amazon SNS topic. func (actor SnsActions) DeleteTopic(ctx context.Context, topicArn string) error { _, err := actor.SnsClient.DeleteTopic(ctx, &sns.DeleteTopicInput{ TopicArn: aws.String(topicArn)}) if err != nil { log.Printf("Couldn't delete topic %v. Here's why: %v\n", topicArn, err) } return err } // SubscribeQueue subscribes an Amazon Simple Queue Service (Amazon SQS) queue to an // Amazon SNS topic. When filterMap is not nil, it is used to specify a filter policy // so that messages are only sent to the queue when the message has the specified attributes. func (actor SnsActions) SubscribeQueue(ctx context.Context, topicArn string, queueArn string, filterMap map[string][]string) (string, error) { var subscriptionArn string var attributes map[string]string if filterMap != nil { filterBytes, err := json.Marshal(filterMap) if err != nil { log.Printf("Couldn't create filter policy, here's why: %v\n", err) return "", err } Publish messages to queues 472 Amazon Simple Queue Service Developer Guide attributes = map[string]string{"FilterPolicy": string(filterBytes)} } output, err := actor.SnsClient.Subscribe(ctx, &sns.SubscribeInput{ Protocol: aws.String("sqs"), TopicArn: aws.String(topicArn), Attributes: attributes, Endpoint: aws.String(queueArn), ReturnSubscriptionArn: true, }) if err != nil { log.Printf("Couldn't susbscribe queue %v to topic %v. Here's why: %v\n", queueArn, topicArn, err) } else { subscriptionArn = *output.SubscriptionArn } return subscriptionArn, err } // Publish publishes a message to an Amazon SNS topic. The message is then sent to all // subscribers. When the topic is a FIFO topic, the message must also contain a group ID // and, when ID-based deduplication is used, a deduplication ID. An optional key- value // filter attribute can be specified so that the message can be filtered according to // a filter policy. func (actor SnsActions) Publish(ctx context.Context, topicArn string, message string, groupId string, dedupId string, filterKey string, filterValue string) error { publishInput := sns.PublishInput{TopicArn: aws.String(topicArn), Message: aws.String(message)} if groupId != "" { publishInput.MessageGroupId = aws.String(groupId) } if dedupId != "" { publishInput.MessageDeduplicationId = aws.String(dedupId) } if filterKey != "" && filterValue != "" { publishInput.MessageAttributes = map[string]types.MessageAttributeValue{ Publish messages to queues 473 Amazon Simple Queue Service Developer Guide filterKey: {DataType: aws.String("String"), StringValue: aws.String(filterValue)}, } } _, err := actor.SnsClient.Publish(ctx, &publishInput) if err != nil { log.Printf("Couldn't publish message to topic %v. Here's why: %v", topicArn, err) } return err } Define a struct that wraps Amazon SQS actions used in this example. import ( "context" "encoding/json" "fmt" "log" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/service/sqs" "github.com/aws/aws-sdk-go-v2/service/sqs/types" ) // SqsActions encapsulates the Amazon Simple Queue Service (Amazon SQS) actions // used in the examples. type SqsActions struct { SqsClient *sqs.Client } // CreateQueue creates an Amazon SQS queue with the specified name. You can specify // whether the queue is created as a FIFO queue. func (actor SqsActions) CreateQueue(ctx context.Context, queueName string, isFifoQueue bool) (string, error) { var queueUrl string queueAttributes := map[string]string{} Publish messages to queues 474 Amazon Simple Queue Service Developer Guide if isFifoQueue { queueAttributes["FifoQueue"] = "true" } queue, err := actor.SqsClient.CreateQueue(ctx, &sqs.CreateQueueInput{ QueueName: aws.String(queueName), Attributes: queueAttributes, }) if err != nil { log.Printf("Couldn't create queue %v. Here's why: %v\n", queueName, err) } else { queueUrl = *queue.QueueUrl } return queueUrl, err } // GetQueueArn uses the GetQueueAttributes action to get the Amazon Resource Name (ARN) // of an Amazon SQS queue. func (actor SqsActions) GetQueueArn(ctx context.Context, queueUrl string) (string, error) { var queueArn string arnAttributeName := types.QueueAttributeNameQueueArn attribute, err := actor.SqsClient.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{ QueueUrl: aws.String(queueUrl), AttributeNames: []types.QueueAttributeName{arnAttributeName}, }) if err != nil { log.Printf("Couldn't get ARN for queue %v. Here's why: %v\n", queueUrl, err) } else { queueArn = attribute.Attributes[string(arnAttributeName)] } return queueArn, err } // AttachSendMessagePolicy uses the SetQueueAttributes action to attach a policy to an // Amazon SQS queue that allows the specified Amazon SNS topic to send messages to the Publish messages
|
sqs-dg-124
|
sqs-dg.pdf
| 124 |
uses the GetQueueAttributes action to get the Amazon Resource Name (ARN) // of an Amazon SQS queue. func (actor SqsActions) GetQueueArn(ctx context.Context, queueUrl string) (string, error) { var queueArn string arnAttributeName := types.QueueAttributeNameQueueArn attribute, err := actor.SqsClient.GetQueueAttributes(ctx, &sqs.GetQueueAttributesInput{ QueueUrl: aws.String(queueUrl), AttributeNames: []types.QueueAttributeName{arnAttributeName}, }) if err != nil { log.Printf("Couldn't get ARN for queue %v. Here's why: %v\n", queueUrl, err) } else { queueArn = attribute.Attributes[string(arnAttributeName)] } return queueArn, err } // AttachSendMessagePolicy uses the SetQueueAttributes action to attach a policy to an // Amazon SQS queue that allows the specified Amazon SNS topic to send messages to the Publish messages to queues 475 Amazon Simple Queue Service // queue. Developer Guide func (actor SqsActions) AttachSendMessagePolicy(ctx context.Context, queueUrl string, queueArn string, topicArn string) error { policyDoc := PolicyDocument{ Version: "2012-10-17", Statement: []PolicyStatement{{ Effect: "Allow", Action: "sqs:SendMessage", Principal: map[string]string{"Service": "sns.amazonaws.com"}, Resource: aws.String(queueArn), Condition: PolicyCondition{"ArnEquals": map[string]string{"aws:SourceArn": topicArn}}, }}, } policyBytes, err := json.Marshal(policyDoc) if err != nil { log.Printf("Couldn't create policy document. Here's why: %v\n", err) return err } _, err = actor.SqsClient.SetQueueAttributes(ctx, &sqs.SetQueueAttributesInput{ Attributes: map[string]string{ string(types.QueueAttributeNamePolicy): string(policyBytes), }, QueueUrl: aws.String(queueUrl), }) if err != nil { log.Printf("Couldn't set send message policy on queue %v. Here's why: %v\n", queueUrl, err) } return err } // PolicyDocument defines a policy document as a Go struct that can be serialized // to JSON. type PolicyDocument struct { Version string Statement []PolicyStatement } // PolicyStatement defines a statement in a policy document. type PolicyStatement struct { Effect string Action string Principal map[string]string `json:",omitempty"` Publish messages to queues 476 Amazon Simple Queue Service Developer Guide Resource *string `json:",omitempty"` Condition PolicyCondition `json:",omitempty"` } // PolicyCondition defines a condition in a policy. type PolicyCondition map[string]map[string]string // GetMessages uses the ReceiveMessage action to get messages from an Amazon SQS queue. func (actor SqsActions) GetMessages(ctx context.Context, queueUrl string, maxMessages int32, waitTime int32) ([]types.Message, error) { var messages []types.Message result, err := actor.SqsClient.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{ QueueUrl: aws.String(queueUrl), MaxNumberOfMessages: maxMessages, WaitTimeSeconds: waitTime, }) if err != nil { log.Printf("Couldn't get messages from queue %v. Here's why: %v\n", queueUrl, err) } else { messages = result.Messages } return messages, err } // DeleteMessages uses the DeleteMessageBatch action to delete a batch of messages from // an Amazon SQS queue. func (actor SqsActions) DeleteMessages(ctx context.Context, queueUrl string, messages []types.Message) error { entries := make([]types.DeleteMessageBatchRequestEntry, len(messages)) for msgIndex := range messages { entries[msgIndex].Id = aws.String(fmt.Sprintf("%v", msgIndex)) entries[msgIndex].ReceiptHandle = messages[msgIndex].ReceiptHandle } _, err := actor.SqsClient.DeleteMessageBatch(ctx, &sqs.DeleteMessageBatchInput{ Entries: entries, QueueUrl: aws.String(queueUrl), }) Publish messages to queues 477 Amazon Simple Queue Service if err != nil { Developer Guide log.Printf("Couldn't delete messages from queue %v. Here's why: %v\n", queueUrl, err) } return err } // DeleteQueue deletes an Amazon SQS queue. func (actor SqsActions) DeleteQueue(ctx context.Context, queueUrl string) error { _, err := actor.SqsClient.DeleteQueue(ctx, &sqs.DeleteQueueInput{ QueueUrl: aws.String(queueUrl)}) if err != nil { log.Printf("Couldn't delete queue %v. Here's why: %v\n", queueUrl, err) } return err } Clean up resources. import ( "context" "fmt" "log" "topics_and_queues/actions" ) // Resources keeps track of AWS resources created during an example and handles // cleanup when the example finishes. type Resources struct { topicArn string queueUrls []string snsActor *actions.SnsActions sqsActor *actions.SqsActions } // Cleanup deletes all AWS resources created during an example. func (resources Resources) Cleanup(ctx context.Context) { defer func() { Publish messages to queues 478 Amazon Simple Queue Service Developer Guide if r := recover(); r != nil { fmt.Println("Something went wrong during cleanup. Use the AWS Management Console\n" + "to remove any remaining resources that were created for this scenario.") } }() var err error if resources.topicArn != "" { log.Printf("Deleting topic %v.\n", resources.topicArn) err = resources.snsActor.DeleteTopic(ctx, resources.topicArn) if err != nil { panic(err) } } for _, queueUrl := range resources.queueUrls { log.Printf("Deleting queue %v.\n", queueUrl) err = resources.sqsActor.DeleteQueue(ctx, queueUrl) if err != nil { panic(err) } } } • For API details, see the following topics in AWS SDK for Go API Reference. • CreateQueue • CreateTopic • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe Publish messages to queues 479 Amazon Simple Queue Service Java SDK for Java 2.x Note Developer Guide There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. package com.example.sns; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.DeleteTopicRequest; import software.amazon.awssdk.services.sns.model.DeleteTopicResponse; import software.amazon.awssdk.services.sns.model.MessageAttributeValue; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; import software.amazon.awssdk.services.sns.model.SetSubscriptionAttributesRequest; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; import software.amazon.awssdk.services.sns.model.UnsubscribeRequest; import software.amazon.awssdk.services.sns.model.UnsubscribeResponse; import software.amazon.awssdk.services.sqs.SqsClient; 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.DeleteQueueRequest; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse; import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest; import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse; import software.amazon.awssdk.services.sqs.model.Message; import software.amazon.awssdk.services.sqs.model.QueueAttributeName; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; Publish messages to queues 480 Amazon Simple Queue Service Developer Guide import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.SqsException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; /** * Before running this Java
|
sqs-dg-125
|
sqs-dg.pdf
| 125 |
Code Examples Repository. package com.example.sns; import software.amazon.awssdk.auth.credentials.EnvironmentVariableCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.DeleteTopicRequest; import software.amazon.awssdk.services.sns.model.DeleteTopicResponse; import software.amazon.awssdk.services.sns.model.MessageAttributeValue; import software.amazon.awssdk.services.sns.model.PublishRequest; import software.amazon.awssdk.services.sns.model.PublishResponse; import software.amazon.awssdk.services.sns.model.SetSubscriptionAttributesRequest; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; import software.amazon.awssdk.services.sns.model.UnsubscribeRequest; import software.amazon.awssdk.services.sns.model.UnsubscribeResponse; import software.amazon.awssdk.services.sqs.SqsClient; 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.DeleteQueueRequest; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.GetQueueAttributesResponse; import software.amazon.awssdk.services.sqs.model.GetQueueUrlRequest; import software.amazon.awssdk.services.sqs.model.GetQueueUrlResponse; import software.amazon.awssdk.services.sqs.model.Message; import software.amazon.awssdk.services.sqs.model.QueueAttributeName; import software.amazon.awssdk.services.sqs.model.ReceiveMessageRequest; Publish messages to queues 480 Amazon Simple Queue Service Developer Guide import software.amazon.awssdk.services.sqs.model.SetQueueAttributesRequest; import software.amazon.awssdk.services.sqs.model.SqsException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * <p> * For more information, see the following documentation topic: * <p> * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get- started.html * <p> * This Java example performs these tasks: * <p> * 1. Gives the user three options to choose from. * 2. Creates an Amazon Simple Notification Service (Amazon SNS) topic. * 3. Creates an Amazon Simple Queue Service (Amazon SQS) queue. * 4. Gets the SQS queue Amazon Resource Name (ARN) attribute. * 5. Attaches an AWS Identity and Access Management (IAM) policy to the queue. * 6. Subscribes to the SQS queue. * 7. Publishes a message to the topic. * 8. Displays the messages. * 9. Deletes the received message. * 10. Unsubscribes from the topic. * 11. Deletes the SNS topic. */ public class SNSWorkflow { public static final String DASHES = new String(new char[80]).replace("\0", "-"); public static void main(String[] args) { final String usage = "\n" + "Usage:\n" + Publish messages to queues 481 Amazon Simple Queue Service Developer Guide " <fifoQueueARN>\n\n" + "Where:\n" + " accountId - Your AWS account Id value."; if (args.length != 1) { System.out.println(usage); System.exit(1); } SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); SqsClient sqsClient = SqsClient.builder() .region(Region.US_EAST_1) .credentialsProvider(EnvironmentVariableCredentialsProvider.create()) .build(); Scanner in = new Scanner(System.in); String accountId = args[0]; String useFIFO; String duplication = "n"; String topicName; String deduplicationID = null; String groupId = null; String topicArn; String sqsQueueName; String sqsQueueUrl; String sqsQueueArn; String subscriptionArn; boolean selectFIFO = false; String message; List<Message> messageList; List<String> filterList = new ArrayList<>(); String msgAttValue = ""; System.out.println(DASHES); System.out.println("Welcome to messaging with topics and queues."); System.out.println("In this scenario, you will create an SNS topic and subscribe an SQS queue to the topic.\n" + Publish messages to queues 482 Amazon Simple Queue Service Developer Guide "You can select from several options for configuring the topic and the subscriptions for the queue.\n" + "You can then post to the topic and see the results in the queue."); System.out.println(DASHES); System.out.println(DASHES); System.out.println("SNS topics can be configured as FIFO (First-In-First- Out).\n" + "FIFO topics deliver messages in order and support deduplication and message filtering.\n" + "Would you like to work with FIFO topics? (y/n)"); useFIFO = in.nextLine(); if (useFIFO.compareTo("y") == 0) { selectFIFO = true; System.out.println("You have selected FIFO"); System.out.println(" Because you have chosen a FIFO topic, deduplication is supported.\n" + " Deduplication IDs are either set in the message or automatically generated from content using a hash function.\n" + " If a message is successfully published to an SNS FIFO topic, any message published and determined to have the same deduplication ID, \n" + " within the five-minute deduplication interval, is accepted but not delivered.\n" + " For more information about deduplication, see https:// docs.aws.amazon.com/sns/latest/dg/fifo-message-dedup.html."); System.out.println( "Would you like to use content-based deduplication instead of entering a deduplication ID? (y/n)"); duplication = in.nextLine(); if (duplication.compareTo("y") == 0) { System.out.println("Please enter a group id value"); groupId = in.nextLine(); } else { System.out.println("Please enter deduplication Id value"); deduplicationID = in.nextLine(); System.out.println("Please enter a group id value"); groupId = in.nextLine(); } } System.out.println(DASHES); Publish messages to queues 483 Amazon Simple Queue Service Developer Guide System.out.println(DASHES); System.out.println("2. Create a topic."); System.out.println("Enter a name for your SNS topic."); topicName = in.nextLine(); if (selectFIFO) { System.out.println("Because you have selected a FIFO topic, '.fifo' must be appended to the topic name."); topicName = topicName + ".fifo"; System.out.println("The name of the topic is " + topicName); topicArn = createFIFO(snsClient, topicName, duplication); System.out.println("The ARN of the FIFO topic is " + topicArn); } else { System.out.println("The name of the topic is " + topicName); topicArn = createSNSTopic(snsClient, topicName); System.out.println("The ARN of the non-FIFO topic is " + topicArn); } System.out.println(DASHES); System.out.println(DASHES); System.out.println("3. Create an SQS queue."); System.out.println("Enter a name for your SQS queue."); sqsQueueName = in.nextLine(); if (selectFIFO) { sqsQueueName = sqsQueueName + ".fifo"; } sqsQueueUrl = createQueue(sqsClient, sqsQueueName, selectFIFO); System.out.println("The queue URL is " + sqsQueueUrl); System.out.println(DASHES); System.out.println(DASHES); System.out.println("4. Get the SQS queue ARN attribute."); sqsQueueArn = getSQSQueueAttrs(sqsClient, sqsQueueUrl); System.out.println("The ARN of the new queue is " + sqsQueueArn); System.out.println(DASHES); System.out.println(DASHES); System.out.println("5. Attach an IAM policy to the queue."); // Define the policy to use. Make sure that you change the REGION if you are // running this
|
sqs-dg-126
|
sqs-dg.pdf
| 126 |
ARN of the non-FIFO topic is " + topicArn); } System.out.println(DASHES); System.out.println(DASHES); System.out.println("3. Create an SQS queue."); System.out.println("Enter a name for your SQS queue."); sqsQueueName = in.nextLine(); if (selectFIFO) { sqsQueueName = sqsQueueName + ".fifo"; } sqsQueueUrl = createQueue(sqsClient, sqsQueueName, selectFIFO); System.out.println("The queue URL is " + sqsQueueUrl); System.out.println(DASHES); System.out.println(DASHES); System.out.println("4. Get the SQS queue ARN attribute."); sqsQueueArn = getSQSQueueAttrs(sqsClient, sqsQueueUrl); System.out.println("The ARN of the new queue is " + sqsQueueArn); System.out.println(DASHES); System.out.println(DASHES); System.out.println("5. Attach an IAM policy to the queue."); // Define the policy to use. Make sure that you change the REGION if you are // running this code Publish messages to queues 484 Amazon Simple Queue Service Developer Guide // in a different region. String policy = """ { "Statement": [ { "Effect": "Allow", "Principal": { "Service": "sns.amazonaws.com" }, "Action": "sqs:SendMessage", "Resource": "arn:aws:sqs:us-east-1:%s:%s", "Condition": { "ArnEquals": { "aws:SourceArn": "arn:aws:sns:us-east-1:%s:%s" } } } ] } """.formatted(accountId, sqsQueueName, accountId, topicName); setQueueAttr(sqsClient, sqsQueueUrl, policy); System.out.println(DASHES); System.out.println(DASHES); System.out.println("6. Subscribe to the SQS queue."); if (selectFIFO) { System.out.println( "If you add a filter to this subscription, then only the filtered messages will be received in the queue.\n" + "For information about message filtering, see https:// docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html\n" + "For this example, you can filter messages by a \"tone\" attribute."); System.out.println("Would you like to filter messages for " + sqsQueueName + "'s subscription to the topic " + topicName + "? (y/n)"); String filterAns = in.nextLine(); if (filterAns.compareTo("y") == 0) { boolean moreAns = false; System.out.println("You can filter messages by one or more of the following \"tone\" attributes."); Publish messages to queues 485 Amazon Simple Queue Service Developer Guide System.out.println("1. cheerful"); System.out.println("2. funny"); System.out.println("3. serious"); System.out.println("4. sincere"); while (!moreAns) { System.out.println("Select a number or choose 0 to end."); String ans = in.nextLine(); switch (ans) { case "1": filterList.add("cheerful"); break; case "2": filterList.add("funny"); break; case "3": filterList.add("serious"); break; case "4": filterList.add("sincere"); break; default: moreAns = true; break; } } } } subscriptionArn = subQueue(snsClient, topicArn, sqsQueueArn, filterList); System.out.println(DASHES); System.out.println(DASHES); System.out.println("7. Publish a message to the topic."); if (selectFIFO) { System.out.println("Would you like to add an attribute to this message? (y/n)"); String msgAns = in.nextLine(); if (msgAns.compareTo("y") == 0) { System.out.println("You can filter messages by one or more of the following \"tone\" attributes."); System.out.println("1. cheerful"); System.out.println("2. funny"); System.out.println("3. serious"); System.out.println("4. sincere"); System.out.println("Select a number or choose 0 to end."); Publish messages to queues 486 Amazon Simple Queue Service Developer Guide String ans = in.nextLine(); switch (ans) { case "1": msgAttValue = "cheerful"; break; case "2": msgAttValue = "funny"; break; case "3": msgAttValue = "serious"; break; default: msgAttValue = "sincere"; break; } System.out.println("Selected value is " + msgAttValue); } System.out.println("Enter a message."); message = in.nextLine(); pubMessageFIFO(snsClient, message, topicArn, msgAttValue, duplication, groupId, deduplicationID); } else { System.out.println("Enter a message."); message = in.nextLine(); pubMessage(snsClient, message, topicArn); } System.out.println(DASHES); System.out.println(DASHES); System.out.println("8. Display the message. Press any key to continue."); in.nextLine(); messageList = receiveMessages(sqsClient, sqsQueueUrl, msgAttValue); for (Message mes : messageList) { System.out.println("Message Id: " + mes.messageId()); System.out.println("Full Message: " + mes.body()); } System.out.println(DASHES); System.out.println(DASHES); System.out.println("9. Delete the received message. Press any key to continue."); in.nextLine(); Publish messages to queues 487 Amazon Simple Queue Service Developer Guide deleteMessages(sqsClient, sqsQueueUrl, messageList); System.out.println(DASHES); System.out.println(DASHES); System.out.println("10. Unsubscribe from the topic and delete the queue. Press any key to continue."); in.nextLine(); unSub(snsClient, subscriptionArn); deleteSQSQueue(sqsClient, sqsQueueName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("11. Delete the topic. Press any key to continue."); in.nextLine(); deleteSNSTopic(snsClient, topicArn); System.out.println(DASHES); System.out.println("The SNS/SQS workflow has completed successfully."); System.out.println(DASHES); } public static void deleteSNSTopic(SnsClient snsClient, String topicArn) { try { DeleteTopicRequest request = DeleteTopicRequest.builder() .topicArn(topicArn) .build(); DeleteTopicResponse result = snsClient.deleteTopic(request); System.out.println("Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void deleteSQSQueue(SqsClient sqsClient, String queueName) { try { GetQueueUrlRequest getQueueRequest = GetQueueUrlRequest.builder() .queueName(queueName) .build(); String queueUrl = sqsClient.getQueueUrl(getQueueRequest).queueUrl(); Publish messages to queues 488 Amazon Simple Queue Service Developer Guide DeleteQueueRequest deleteQueueRequest = DeleteQueueRequest.builder() .queueUrl(queueUrl) .build(); sqsClient.deleteQueue(deleteQueueRequest); System.out.println(queueName + " was successfully deleted."); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void unSub(SnsClient snsClient, String subscriptionArn) { try { UnsubscribeRequest request = UnsubscribeRequest.builder() .subscriptionArn(subscriptionArn) .build(); UnsubscribeResponse result = snsClient.unsubscribe(request); System.out.println("Status was " + result.sdkHttpResponse().statusCode() + "\nSubscription was removed for " + request.subscriptionArn()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void deleteMessages(SqsClient sqsClient, String queueUrl, List<Message> messages) { try { List<DeleteMessageBatchRequestEntry> entries = new ArrayList<>(); for (Message msg : messages) { DeleteMessageBatchRequestEntry entry = DeleteMessageBatchRequestEntry.builder() .id(msg.messageId()) .build(); entries.add(entry); } Publish messages to queues 489 Amazon Simple Queue Service Developer Guide DeleteMessageBatchRequest deleteMessageBatchRequest = DeleteMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(entries) .build(); sqsClient.deleteMessageBatch(deleteMessageBatchRequest); System.out.println("The batch delete of messages was successful"); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static List<Message> receiveMessages(SqsClient sqsClient, String queueUrl, String msgAttValue) { try { if (msgAttValue.isEmpty()) { ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder() .queueUrl(queueUrl) .maxNumberOfMessages(5) .build(); return sqsClient.receiveMessage(receiveMessageRequest).messages(); } else { // We know there are filters on the message. ReceiveMessageRequest receiveRequest = ReceiveMessageRequest.builder() .queueUrl(queueUrl) .messageAttributeNames(msgAttValue)
|
sqs-dg-127
|
sqs-dg.pdf
| 127 |
messages) { try { List<DeleteMessageBatchRequestEntry> entries = new ArrayList<>(); for (Message msg : messages) { DeleteMessageBatchRequestEntry entry = DeleteMessageBatchRequestEntry.builder() .id(msg.messageId()) .build(); entries.add(entry); } Publish messages to queues 489 Amazon Simple Queue Service Developer Guide DeleteMessageBatchRequest deleteMessageBatchRequest = DeleteMessageBatchRequest.builder() .queueUrl(queueUrl) .entries(entries) .build(); sqsClient.deleteMessageBatch(deleteMessageBatchRequest); System.out.println("The batch delete of messages was successful"); } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static List<Message> receiveMessages(SqsClient sqsClient, String queueUrl, String msgAttValue) { try { if (msgAttValue.isEmpty()) { ReceiveMessageRequest receiveMessageRequest = ReceiveMessageRequest.builder() .queueUrl(queueUrl) .maxNumberOfMessages(5) .build(); return sqsClient.receiveMessage(receiveMessageRequest).messages(); } else { // We know there are filters on the message. ReceiveMessageRequest receiveRequest = ReceiveMessageRequest.builder() .queueUrl(queueUrl) .messageAttributeNames(msgAttValue) // Include other message attributes if needed. .maxNumberOfMessages(5) .build(); return sqsClient.receiveMessage(receiveRequest).messages(); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return null; Publish messages to queues 490 Amazon Simple Queue Service } Developer Guide public static void pubMessage(SnsClient snsClient, String message, String topicArn) { try { PublishRequest request = PublishRequest.builder() .message(message) .topicArn(topicArn) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static void pubMessageFIFO(SnsClient snsClient, String message, String topicArn, String msgAttValue, String duplication, String groupId, String deduplicationID) { try { PublishRequest request; // Means the user did not choose to use a message attribute. if (msgAttValue.isEmpty()) { if (duplication.compareTo("y") == 0) { request = PublishRequest.builder() .message(message) .messageGroupId(groupId) .topicArn(topicArn) .build(); } else { request = PublishRequest.builder() .message(message) .messageDeduplicationId(deduplicationID) .messageGroupId(groupId) Publish messages to queues 491 Amazon Simple Queue Service Developer Guide .topicArn(topicArn) .build(); } } else { Map<String, MessageAttributeValue> messageAttributes = new HashMap<>(); messageAttributes.put(msgAttValue, MessageAttributeValue.builder() .dataType("String") .stringValue("true") .build()); if (duplication.compareTo("y") == 0) { request = PublishRequest.builder() .message(message) .messageGroupId(groupId) .topicArn(topicArn) .build(); } else { // Create a publish request with the message and attributes. request = PublishRequest.builder() .topicArn(topicArn) .message(message) .messageDeduplicationId(deduplicationID) .messageGroupId(groupId) .messageAttributes(messageAttributes) .build(); } } // Publish the message to the topic. PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } // Subscribe to the SQS queue. Publish messages to queues 492 Amazon Simple Queue Service Developer Guide public static String subQueue(SnsClient snsClient, String topicArn, String queueArn, List<String> filterList) { try { SubscribeRequest request; if (filterList.isEmpty()) { // No filter subscription is added. request = SubscribeRequest.builder() .protocol("sqs") .endpoint(queueArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("The queue " + queueArn + " has been subscribed to the topic " + topicArn + "\n" + "with the subscription ARN " + result.subscriptionArn()); return result.subscriptionArn(); } else { request = SubscribeRequest.builder() .protocol("sqs") .endpoint(queueArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("The queue " + queueArn + " has been subscribed to the topic " + topicArn + "\n" + "with the subscription ARN " + result.subscriptionArn()); String attributeName = "FilterPolicy"; Gson gson = new Gson(); String jsonString = "{\"tone\": []}"; JsonObject jsonObject = gson.fromJson(jsonString, JsonObject.class); JsonArray toneArray = jsonObject.getAsJsonArray("tone"); for (String value : filterList) { toneArray.add(new JsonPrimitive(value)); } String updatedJsonString = gson.toJson(jsonObject); System.out.println(updatedJsonString); Publish messages to queues 493 Amazon Simple Queue Service Developer Guide SetSubscriptionAttributesRequest attRequest = SetSubscriptionAttributesRequest.builder() .subscriptionArn(result.subscriptionArn()) .attributeName(attributeName) .attributeValue(updatedJsonString) .build(); snsClient.setSubscriptionAttributes(attRequest); return result.subscriptionArn(); } } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } // Attach a policy to the queue. public static void setQueueAttr(SqsClient sqsClient, String queueUrl, String policy) { try { Map<software.amazon.awssdk.services.sqs.model.QueueAttributeName, String> attrMap = new HashMap<>(); attrMap.put(QueueAttributeName.POLICY, policy); SetQueueAttributesRequest attributesRequest = SetQueueAttributesRequest.builder() .queueUrl(queueUrl) .attributes(attrMap) .build(); sqsClient.setQueueAttributes(attributesRequest); System.out.println("The policy has been successfully attached."); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } public static String getSQSQueueAttrs(SqsClient sqsClient, String queueUrl) { // Specify the attributes to retrieve. List<QueueAttributeName> atts = new ArrayList<>(); Publish messages to queues 494 Amazon Simple Queue Service Developer Guide atts.add(QueueAttributeName.QUEUE_ARN); GetQueueAttributesRequest attributesRequest = GetQueueAttributesRequest.builder() .queueUrl(queueUrl) .attributeNames(atts) .build(); GetQueueAttributesResponse response = sqsClient.getQueueAttributes(attributesRequest); Map<String, String> queueAtts = response.attributesAsStrings(); for (Map.Entry<String, String> queueAtt : queueAtts.entrySet()) return queueAtt.getValue(); return ""; } public static String createQueue(SqsClient sqsClient, String queueName, Boolean selectFIFO) { try { System.out.println("\nCreate Queue"); if (selectFIFO) { Map<QueueAttributeName, String> attrs = new HashMap<>(); attrs.put(QueueAttributeName.FIFO_QUEUE, "true"); CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .attributes(attrs) .build(); sqsClient.createQueue(createQueueRequest); System.out.println("\nGet queue url"); GetQueueUrlResponse getQueueUrlResponse = sqsClient .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()); return getQueueUrlResponse.queueUrl(); } else { CreateQueueRequest createQueueRequest = CreateQueueRequest.builder() .queueName(queueName) .build(); sqsClient.createQueue(createQueueRequest); System.out.println("\nGet queue url"); Publish messages to queues 495 Amazon Simple Queue Service Developer Guide GetQueueUrlResponse getQueueUrlResponse = sqsClient .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()); return getQueueUrlResponse.queueUrl(); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static String createSNSTopic(SnsClient snsClient, String topicName) { CreateTopicResponse result; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static String createFIFO(SnsClient snsClient, String topicName, String duplication) { try { // Create a FIFO topic by using the SNS service client. Map<String, String> topicAttributes = new HashMap<>(); if (duplication.compareTo("n") == 0) { topicAttributes.put("FifoTopic", "true"); topicAttributes.put("ContentBasedDeduplication", "false"); } else { topicAttributes.put("FifoTopic", "true"); topicAttributes.put("ContentBasedDeduplication", "true"); } CreateTopicRequest topicRequest
|
sqs-dg-128
|
sqs-dg.pdf
| 128 |
getQueueUrlResponse = sqsClient .getQueueUrl(GetQueueUrlRequest.builder().queueName(queueName).build()); return getQueueUrlResponse.queueUrl(); } } catch (SqsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static String createSNSTopic(SnsClient snsClient, String topicName) { CreateTopicResponse result; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static String createFIFO(SnsClient snsClient, String topicName, String duplication) { try { // Create a FIFO topic by using the SNS service client. Map<String, String> topicAttributes = new HashMap<>(); if (duplication.compareTo("n") == 0) { topicAttributes.put("FifoTopic", "true"); topicAttributes.put("ContentBasedDeduplication", "false"); } else { topicAttributes.put("FifoTopic", "true"); topicAttributes.put("ContentBasedDeduplication", "true"); } CreateTopicRequest topicRequest = CreateTopicRequest.builder() Publish messages to queues 496 Amazon Simple Queue Service Developer Guide .name(topicName) .attributes(topicAttributes) .build(); CreateTopicResponse response = snsClient.createTopic(topicRequest); return response.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } } • For API details, see the following topics in AWS SDK for Java 2.x API Reference. • CreateQueue • CreateTopic • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe JavaScript SDK for JavaScript (v3) Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. Publish messages to queues 497 Amazon Simple Queue Service Developer Guide This is the entry point for this scenario. import { SNSClient } from "@aws-sdk/client-sns"; import { SQSClient } from "@aws-sdk/client-sqs"; import { TopicsQueuesWkflw } from "./TopicsQueuesWkflw.js"; import { Prompter } from "@aws-doc-sdk-examples/lib/prompter.js"; export const startSnsWorkflow = () => { const snsClient = new SNSClient({}); const sqsClient = new SQSClient({}); const prompter = new Prompter(); const logger = console; const wkflw = new TopicsQueuesWkflw(snsClient, sqsClient, prompter, logger); wkflw.start(); }; The preceding code provides the necessary dependencies and starts the scenario. The next section contains the bulk of the example. const toneChoices = [ { name: "cheerful", value: "cheerful" }, { name: "funny", value: "funny" }, { name: "serious", value: "serious" }, { name: "sincere", value: "sincere" }, ]; export class TopicsQueuesWkflw { // SNS topic is configured as First-In-First-Out isFifo = true; // Automatic content-based deduplication is enabled. autoDedup = false; snsClient; sqsClient; topicName; topicArn; Publish messages to queues 498 Amazon Simple Queue Service Developer Guide subscriptionArns = []; /** * @type {{ queueName: string, queueArn: string, queueUrl: string, policy?: string }[]} */ queues = []; prompter; /** * @param {import('@aws-sdk/client-sns').SNSClient} snsClient * @param {import('@aws-sdk/client-sqs').SQSClient} sqsClient * @param {import('../../libs/prompter.js').Prompter} prompter * @param {import('../../libs/logger.js').Logger} logger */ constructor(snsClient, sqsClient, prompter, logger) { this.snsClient = snsClient; this.sqsClient = sqsClient; this.prompter = prompter; this.logger = logger; } async welcome() { await this.logger.log(MESSAGES.description); } async confirmFifo() { await this.logger.log(MESSAGES.snsFifoDescription); this.isFifo = await this.prompter.confirm({ message: MESSAGES.snsFifoPrompt, }); if (this.isFifo) { this.logger.logSeparator(MESSAGES.headerDedup); await this.logger.log(MESSAGES.deduplicationNotice); await this.logger.log(MESSAGES.deduplicationDescription); this.autoDedup = await this.prompter.confirm({ message: MESSAGES.deduplicationPrompt, }); } } async createTopic() { await this.logger.log(MESSAGES.creatingTopics); this.topicName = await this.prompter.input({ Publish messages to queues 499 Amazon Simple Queue Service Developer Guide message: MESSAGES.topicNamePrompt, }); if (this.isFifo) { this.topicName += ".fifo"; this.logger.logSeparator(MESSAGES.headerFifoNaming); await this.logger.log(MESSAGES.appendFifoNotice); } const response = await this.snsClient.send( new CreateTopicCommand({ Name: this.topicName, Attributes: { FifoTopic: this.isFifo ? "true" : "false", ...(this.autoDedup ? { ContentBasedDeduplication: "true" } : {}), }, }), ); this.topicArn = response.TopicArn; await this.logger.log( MESSAGES.topicCreatedNotice .replace("${TOPIC_NAME}", this.topicName) .replace("${TOPIC_ARN}", this.topicArn), ); } async createQueues() { await this.logger.log(MESSAGES.createQueuesNotice); // Increase this number to add more queues. const maxQueues = 2; for (let i = 0; i < maxQueues; i++) { await this.logger.log(MESSAGES.queueCount.replace("${COUNT}", i + 1)); let queueName = await this.prompter.input({ message: MESSAGES.queueNamePrompt.replace( "${EXAMPLE_NAME}", i === 0 ? "good-news" : "bad-news", ), }); if (this.isFifo) { queueName += ".fifo"; await this.logger.log(MESSAGES.appendFifoNotice); Publish messages to queues 500 Amazon Simple Queue Service } Developer Guide const response = await this.sqsClient.send( new CreateQueueCommand({ QueueName: queueName, Attributes: { ...(this.isFifo ? { FifoQueue: "true" } : {}) }, }), ); const { Attributes } = await this.sqsClient.send( new GetQueueAttributesCommand({ QueueUrl: response.QueueUrl, AttributeNames: ["QueueArn"], }), ); this.queues.push({ queueName, queueArn: Attributes.QueueArn, queueUrl: response.QueueUrl, }); await this.logger.log( MESSAGES.queueCreatedNotice .replace("${QUEUE_NAME}", queueName) .replace("${QUEUE_URL}", response.QueueUrl) .replace("${QUEUE_ARN}", Attributes.QueueArn), ); } } async attachQueueIamPolicies() { for (const [index, queue] of this.queues.entries()) { const policy = JSON.stringify( { Statement: [ { Effect: "Allow", Principal: { Service: "sns.amazonaws.com", }, Action: "sqs:SendMessage", Resource: queue.queueArn, Condition: { Publish messages to queues 501 Amazon Simple Queue Service Developer Guide ArnEquals: { "aws:SourceArn": this.topicArn, }, }, }, ], }, null, 2, ); if (index !== 0) { this.logger.logSeparator(); } await this.logger.log(MESSAGES.attachPolicyNotice); console.log(policy); const addPolicy = await this.prompter.confirm({ message: MESSAGES.addPolicyConfirmation.replace( "${QUEUE_NAME}", queue.queueName, ), }); if (addPolicy) { await this.sqsClient.send( new SetQueueAttributesCommand({ QueueUrl: queue.queueUrl, Attributes: { Policy: policy, }, }), ); queue.policy = policy; } else { await this.logger.log( MESSAGES.policyNotAttachedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); } } } Publish messages to queues 502 Amazon Simple Queue Service Developer Guide async subscribeQueuesToTopic() { for (const [index, queue] of this.queues.entries()) { /** * @type {import('@aws-sdk/client-sns').SubscribeCommandInput} */ const subscribeParams = { TopicArn: this.topicArn, Protocol: "sqs", Endpoint: queue.queueArn, };
|
sqs-dg-129
|
sqs-dg.pdf
| 129 |
"aws:SourceArn": this.topicArn, }, }, }, ], }, null, 2, ); if (index !== 0) { this.logger.logSeparator(); } await this.logger.log(MESSAGES.attachPolicyNotice); console.log(policy); const addPolicy = await this.prompter.confirm({ message: MESSAGES.addPolicyConfirmation.replace( "${QUEUE_NAME}", queue.queueName, ), }); if (addPolicy) { await this.sqsClient.send( new SetQueueAttributesCommand({ QueueUrl: queue.queueUrl, Attributes: { Policy: policy, }, }), ); queue.policy = policy; } else { await this.logger.log( MESSAGES.policyNotAttachedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); } } } Publish messages to queues 502 Amazon Simple Queue Service Developer Guide async subscribeQueuesToTopic() { for (const [index, queue] of this.queues.entries()) { /** * @type {import('@aws-sdk/client-sns').SubscribeCommandInput} */ const subscribeParams = { TopicArn: this.topicArn, Protocol: "sqs", Endpoint: queue.queueArn, }; let tones = []; if (this.isFifo) { if (index === 0) { await this.logger.log(MESSAGES.fifoFilterNotice); } tones = await this.prompter.checkbox({ message: MESSAGES.fifoFilterSelect.replace( "${QUEUE_NAME}", queue.queueName, ), choices: toneChoices, }); if (tones.length) { subscribeParams.Attributes = { FilterPolicyScope: "MessageAttributes", FilterPolicy: JSON.stringify({ tone: tones, }), }; } } const { SubscriptionArn } = await this.snsClient.send( new SubscribeCommand(subscribeParams), ); this.subscriptionArns.push(SubscriptionArn); await this.logger.log( MESSAGES.queueSubscribedNotice .replace("${QUEUE_NAME}", queue.queueName) Publish messages to queues 503 Amazon Simple Queue Service Developer Guide .replace("${TOPIC_NAME}", this.topicName) .replace("${TONES}", tones.length ? tones.join(", ") : "none"), ); } } async publishMessages() { const message = await this.prompter.input({ message: MESSAGES.publishMessagePrompt, }); let groupId; let deduplicationId; let choices; if (this.isFifo) { await this.logger.log(MESSAGES.groupIdNotice); groupId = await this.prompter.input({ message: MESSAGES.groupIdPrompt, }); if (this.autoDedup === false) { await this.logger.log(MESSAGES.deduplicationIdNotice); deduplicationId = await this.prompter.input({ message: MESSAGES.deduplicationIdPrompt, }); } choices = await this.prompter.checkbox({ message: MESSAGES.messageAttributesPrompt, choices: toneChoices, }); } await this.snsClient.send( new PublishCommand({ TopicArn: this.topicArn, Message: message, ...(groupId ? { MessageGroupId: groupId, } : {}), ...(deduplicationId Publish messages to queues 504 Amazon Simple Queue Service ? { Developer Guide MessageDeduplicationId: deduplicationId, } : {}), ...(choices ? { MessageAttributes: { tone: { DataType: "String.Array", StringValue: JSON.stringify(choices), }, }, } : {}), }), ); const publishAnother = await this.prompter.confirm({ message: MESSAGES.publishAnother, }); if (publishAnother) { await this.publishMessages(); } } async receiveAndDeleteMessages() { for (const queue of this.queues) { const { Messages } = await this.sqsClient.send( new ReceiveMessageCommand({ QueueUrl: queue.queueUrl, }), ); if (Messages) { await this.logger.log( MESSAGES.messagesReceivedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); console.log(Messages); await this.sqsClient.send( Publish messages to queues 505 Amazon Simple Queue Service Developer Guide new DeleteMessageBatchCommand({ QueueUrl: queue.queueUrl, Entries: Messages.map((message) => ({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle, })), }), ); } else { await this.logger.log( MESSAGES.noMessagesReceivedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); } } const deleteAndPoll = await this.prompter.confirm({ message: MESSAGES.deleteAndPollConfirmation, }); if (deleteAndPoll) { await this.receiveAndDeleteMessages(); } } async destroyResources() { for (const subscriptionArn of this.subscriptionArns) { await this.snsClient.send( new UnsubscribeCommand({ SubscriptionArn: subscriptionArn }), ); } for (const queue of this.queues) { await this.sqsClient.send( new DeleteQueueCommand({ QueueUrl: queue.queueUrl }), ); } if (this.topicArn) { await this.snsClient.send( new DeleteTopicCommand({ TopicArn: this.topicArn }), ); Publish messages to queues 506 Amazon Simple Queue Service Developer Guide } } async start() { console.clear(); try { this.logger.logSeparator(MESSAGES.headerWelcome); await this.welcome(); this.logger.logSeparator(MESSAGES.headerFifo); await this.confirmFifo(); this.logger.logSeparator(MESSAGES.headerCreateTopic); await this.createTopic(); this.logger.logSeparator(MESSAGES.headerCreateQueues); await this.createQueues(); this.logger.logSeparator(MESSAGES.headerAttachPolicy); await this.attachQueueIamPolicies(); this.logger.logSeparator(MESSAGES.headerSubscribeQueues); await this.subscribeQueuesToTopic(); this.logger.logSeparator(MESSAGES.headerPublishMessage); await this.publishMessages(); this.logger.logSeparator(MESSAGES.headerReceiveMessages); await this.receiveAndDeleteMessages(); } catch (err) { console.error(err); } finally { await this.destroyResources(); } } } • For API details, see the following topics in AWS SDK for JavaScript API Reference. • CreateQueue • CreateTopic • DeleteMessageBatch • DeleteQueue • DeleteTopic • GetQueueAttributes • Publish Publish messages to queues 507 Amazon Simple Queue Service Developer Guide • ReceiveMessage • SetQueueAttributes • Subscribe • Unsubscribe Kotlin SDK for Kotlin Note There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository. package com.example.sns import aws.sdk.kotlin.services.sns.SnsClient import aws.sdk.kotlin.services.sns.model.CreateTopicRequest import aws.sdk.kotlin.services.sns.model.DeleteTopicRequest import aws.sdk.kotlin.services.sns.model.PublishRequest import aws.sdk.kotlin.services.sns.model.SetSubscriptionAttributesRequest import aws.sdk.kotlin.services.sns.model.SubscribeRequest import aws.sdk.kotlin.services.sns.model.UnsubscribeRequest import aws.sdk.kotlin.services.sqs.SqsClient import aws.sdk.kotlin.services.sqs.model.CreateQueueRequest import aws.sdk.kotlin.services.sqs.model.DeleteMessageBatchRequest import aws.sdk.kotlin.services.sqs.model.DeleteMessageBatchRequestEntry import aws.sdk.kotlin.services.sqs.model.DeleteQueueRequest import aws.sdk.kotlin.services.sqs.model.GetQueueAttributesRequest import aws.sdk.kotlin.services.sqs.model.GetQueueUrlRequest import aws.sdk.kotlin.services.sqs.model.Message import aws.sdk.kotlin.services.sqs.model.QueueAttributeName import aws.sdk.kotlin.services.sqs.model.ReceiveMessageRequest import aws.sdk.kotlin.services.sqs.model.SetQueueAttributesRequest import com.google.gson.Gson import com.google.gson.JsonObject import com.google.gson.JsonPrimitive import java.util.Scanner Publish messages to queues 508 Amazon Simple Queue Service /** Developer Guide Before running this Kotlin code example, set up your development environment, including your AWS credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html This Kotlin example performs the following tasks: 1. Gives the user three options to choose from. 2. Creates an Amazon Simple Notification Service (Amazon SNS) topic. 3. Creates an Amazon Simple Queue Service (Amazon SQS) queue. 4. Gets the SQS queue Amazon Resource Name (ARN) attribute. 5. Attaches an AWS Identity and Access Management (IAM) policy to the queue. 6. Subscribes to the SQS queue. 7. Publishes a message to the topic. 8. Displays the messages. 9. Deletes the received message. 10. Unsubscribes from the topic. 11. Deletes the SNS topic. */ val DASHES: String = String(CharArray(80)).replace("\u0000", "-") suspend fun main() { val input = Scanner(System.`in`) val useFIFO: String var duplication = "n" var topicName: String var deduplicationID: String? = null var groupId: String? = null val topicArn: String? var sqsQueueName: String val sqsQueueUrl: String? val sqsQueueArn: String val subscriptionArn: String? var selectFIFO = false val message: String val messageList: List<Message?>?
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.