

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 为 Amazon SQS 队列配置标签
<a name="sqs-java-add-update-remove-tag-queue"></a>

使用 cost-allocation 标签来帮助组织和标识 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);
```