

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Amazon SQS Java 開發套件範例
<a name="sqs-java-tutorials"></a>

 適用於 Java 的 AWS SDK 可讓您建置與 Amazon SQS 和其他 互動的 Java 應用程式 AWS 服務。
+ 若要安裝和設定 SDK，請參閱《AWS SDK for Java 2.x 開發人員指南》**中的[入門](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/getting-started.html)。
+ 如需基本佇列操作，例如建立佇列或傳送訊息，請參閱《 *AWS SDK for Java 2.x 開發人員指南*》中的[使用 Amazon SQS 訊息佇列](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/sqs-examples.html)。
+ 本指南也包含其他 Amazon SQS 功能的範例，例如：
  + [搭配 Amazon SQS 佇列使用伺服器端加密](sqs-java-configure-sse.md)
  + [設定 Amazon SQS 佇列的標籤](sqs-java-add-update-remove-tag-queue.md)
  + [將訊息屬性傳送至 Amazon SQS 佇列](sqs-java-send-message-with-attributes.md)

# 搭配 Amazon SQS 佇列使用伺服器端加密
<a name="sqs-java-configure-sse"></a>

使用 適用於 Java 的 AWS SDK 將伺服器端加密 (SSE) 新增至 Amazon SQS 佇列。每個佇列都使用 AWS Key Management Service (AWS KMS) KMS 金鑰來產生資料加密金鑰。此範例使用 Amazon SQS 的 AWS 受管 KMS 金鑰。

如需使用 SSE 和 KMS 金鑰之角色的相關資訊，請參閱 [Amazon SQS 中的靜態加密](sqs-server-side-encryption.md)。

## 將 SSE 新增到現有佇列
<a name="sqs-java-configure-sse-existing-queue"></a>

若要啟用現有佇列的伺服器端加密，請使用 `[SetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html)` 方法來設定 `KmsMasterKeyId` 屬性。

下列程式碼範例會將 設定為 AWS KMS key Amazon SQS 的 AWS 受管 KMS 金鑰。此範例也會將 [AWS KMS key 重複使用期間](sqs-server-side-encryption.md#sqs-sse-key-terms)設定為 140 秒。

 執行範例程式碼之前，請確定您已設定 AWS 登入資料。如需詳細資訊，請參閱《 *AWS SDK for Java 2.x 開發人員指南*》中的[設定開發的 AWS 登入資料和區域](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html#setup-credentials)。

```
    public static void addEncryption(String queueName, String kmsMasterKeyAlias) {
        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();
        }
    }
```

## 停用佇列的 SSE
<a name="sqs-java-disable-sse"></a>

若要停用現有佇列的伺服器端加密，請使用 `SetQueueAttributes` 方法將 `KmsMasterKeyId` 屬性設定為空白字串。

**重要**  
`null` 不是 `KmsMasterKeyId` 的有效值。

## 使用 SSE 建立佇列
<a name="sqs-java-configure-sse-create-queue"></a>

若要在建立佇列時啟用 SSE，請將 `KmsMasterKeyId` 屬性新增至 `[CreateQueue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_CreateQueue.html)` API 方法。

以下範例顯示如何建立啟用 SSE 的新佇列。佇列使用 Amazon SQS 的 AWS 受管 KMS 金鑰。此範例也會將 [AWS KMS key 重複使用期間](sqs-server-side-encryption.md#sqs-sse-key-terms)設定為 160 秒。

 執行範例程式碼之前，請確定您已設定 AWS 登入資料。如需詳細資訊，請參閱《 *AWS SDK for Java 2.x 開發人員指南*》中的[設定用於開發的 AWS 登入資料和區域](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html#setup-credentials)。

```
// 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);
```

## 擷取 SSE 屬性
<a name="sqs-java-get-sse-attributes"></a>

如需擷取佇列屬性的相關資訊，請參閱《Amazon Simple Queue Service API 參考》**中的[範例](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueAttributes.html#API_GetQueueAttributes_Examples)。

若要擷取特定佇列的 KMS 金鑰 ID 或資料金鑰重複使用期間，請執行 `[GetQueueAttributes](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_GetQueueAttributes.html)` 方法並擷取 `KmsMasterKeyId` 和 `KmsDataKeyReusePeriodSeconds` 值。

# 設定 Amazon SQS 佇列的標籤
<a name="sqs-java-add-update-remove-tag-queue"></a>

使用成本分配標籤來幫助組織和識別您的 Amazon SQS 佇列。下列範例示範如何使用 適用於 Java 的 AWS SDK設定標籤。如需詳細資訊，請參閱[Amazon SQS 成本分配標籤](sqs-queue-tags.md)。

 執行範例程式碼之前，請確定您已設定 AWS 登入資料。如需詳細資訊，請參閱《 *AWS SDK for Java 2.x 開發人員指南*》中的[設定用於開發的 AWS 登入資料和區域](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html#setup-credentials)。

## 列出標籤
<a name="sqs-java-list-tags"></a>

若要列出佇列的標籤，請使用 `ListQueueTags` 方法。

```
// 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);
System.out.println(String.format("ListQueueTags: \tTags for queue %s are %s.\n",
                queueName, listQueueTagsResponse.tags() ));
```

## 新增或更新標籤
<a name="sqs-java-add-tags"></a>

若要新增或更新佇列的標籤值，請使用 `TagQueue` 方法。

```
 // 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);
```

## 移除標籤
<a name="sqs-java-remove-tags"></a>

若要移除佇列的一個或多個標籤，請使用 `UntagQueue` 方法。下列範例會移除 `Accounting ID` 標籤。

```
 
// Create the UntagQueueRequest.
final UntagQueueRequest untagQueueRequest = UntagQueueRequest.builder()
        .queueUrl(queueUrl)
        .tagKeys("Accounting ID")
        .build();
        
// Remove the tag from this queue.
sqsClient.untagQueue(untagQueueRequest);
```

# 將訊息屬性傳送至 Amazon SQS 佇列
<a name="sqs-java-send-message-with-attributes"></a>

您可使用*訊息屬性*提供有關訊息的結構化中繼資料項目 (例如，時間戳記、地理空間資料、簽章和識別碼)。如需詳細資訊，請參閱[Amazon SQS 訊息屬性](sqs-message-metadata.md#sqs-message-attributes)。

 執行範例程式碼之前，請確定您已設定 AWS 登入資料。如需詳細資訊，請參閱《 *AWS SDK for Java 2.x 開發人員指南*》中的[設定用於開發的 AWS 登入資料和區域](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup.html#setup-credentials)。

## 定義屬性
<a name="sqs-java-define-attributes"></a>

為了定義訊息的屬性，請新增以下使用 `[MessageAttributeValue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_MessageAttributeValue.html)` 資料類型的程式碼。如需詳細資訊，請參閱[訊息屬性元件](sqs-message-metadata.md#message-attribute-components)及[訊息屬性資料類型](sqs-message-metadata.md#message-attribute-data-types)。

 適用於 Java 的 AWS SDK 會自動計算訊息內文和訊息屬性檢查總和，並將其與 Amazon SQS 傳回的資料進行比較。如需詳細資訊，請參閱 *[AWS SDK for Java 2.x 開發人員指南](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/)*以及適用於其他程式設計語言的 [計算訊息屬性的 MD5 訊息摘要](sqs-message-metadata.md#sqs-attributes-md5-message-digest-calculation)。

------
#### [ String ]

此範例將名為 `Name` 的 `String` 屬性定義為 `Jane` 的值。

```
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("Name", new MessageAttributeValue()
.withDataType("String")
.withStringValue("Jane"));
```

------
#### [ Number ]

此範例將名為 `AccurateWeight` 的 `Number` 屬性定義為 `230.000000000000000001` 的值。

```
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("AccurateWeight", new MessageAttributeValue()
.withDataType("Number")
.withStringValue("230.000000000000000001"));
```

------
#### [ Binary ]

此範例將名為 `ByteArray` 的 `Binary` 屬性定義為未初始化 10 位元組陣列的值。

```
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("ByteArray", new MessageAttributeValue()
.withDataType("Binary")
.withBinaryValue(ByteBuffer.wrap(new byte[10])));
```

------
#### [ String (custom) ]

此範例將名為 `EmployeeId` 的自訂屬性 `String.EmployeeId` 定義為 `ABC123456` 的值。

```
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("EmployeeId", new MessageAttributeValue()
.withDataType("String.EmployeeId")
.withStringValue("ABC123456"));
```

------
#### [ Number (custom) ]

此範例將名為 `AccountId` 的自訂屬性 `Number.AccountId` 定義為 `000123456` 的值。

```
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("AccountId", new MessageAttributeValue()
.withDataType("Number.AccountId")
.withStringValue("000123456"));
```

**注意**  
由於基本資料類型為 `Number`，`[ReceiveMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_ReceiveMessage.html)` 動作會傳回 `123456`。

------
#### [ Binary (custom) ]

此範例將名為 `ApplicationIcon` 的自訂屬性 `Binary.JPEG` 定義為未初始化 10 位元組陣列的值。

```
final Map<String, MessageAttributeValue> messageAttributes = new HashMap<>();
messageAttributes.put("ApplicationIcon", new MessageAttributeValue()
.withDataType("Binary.JPEG")
.withBinaryValue(ByteBuffer.wrap(new byte[10])));
```

------

## 傳送具有屬性的訊息
<a name="sqs-java-send-attributes"></a>

此範例會在傳送訊息之前將屬性新增至 `SendMessageRequest`。

```
// 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);
```

**重要**  
如果您將訊息傳送到 先進先出 (FIFO) 佇列，請確保 `sendMessage` 方法在您提供訊息群組 ID *之後*才執行。  
如果您使用 `[SendMessageBatch](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html)` 方法，而非 `[SendMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html)`，您必須為批次中每個訊息指定訊息屬性。