

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Amazon SQS Java SDK 예제
<a name="sqs-java-tutorials"></a>

AWS SDK for Java를 사용하면 Amazon SQS 및 기타 AWS 서비스와 상호 작용하는 Java 애플리케이션을 구축할 수 있습니다.
+ 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>

 AWS SDK for Java 를 사용하여 Amazon SQS 대기열에 서버 측 암호화(SSE)를 추가합니다. 각 대기열은 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` 속성을 설정합니다.

다음 코드 예제에서는를 Amazon SQS의 AWS 관리형 KMS 키 AWS KMS key 로 설정합니다. 또한 이 예제에서는 [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를 활성화하려면 `[CreateQueue](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_CreateQueue.html)` API 메서드에 `KmsMasterKeyId` 속성을 추가합니다.

다음 예제에서는 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 대기열을 구성하고 식별할 수 있습니다. 다음 예제에서는 AWS SDK for Java를 사용하여 태그를 구성하는 방법을 보여줍니다. 자세한 내용은 [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) 섹션을 참조하세요.

는 메시지 본문 및 메시지 속성 체크섬을 AWS SDK for Java 자동으로 계산하고 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 ]

이 예제에서는 값 `Jane`을 사용하여 `Name`이라는 `String` 속성을 정의합니다.

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

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

이 예제에서는 값 `230.000000000000000001`을 사용하여 `AccurateWeight`이라는 `Number` 속성을 정의합니다.

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

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

이 예제에서는 초기화되지 않은 10바이트 어레이의 값을 사용하여 `ByteArray`라는 `Binary` 속성을 정의합니다.

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

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

이 예제에서는 값 `ABC123456`을 사용하여 `EmployeeId`라는 사용자 지정 속성 `String.EmployeeId`를 정의합니다.

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

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

이 예제에서는 값 `000123456`을 사용하여 `AccountId`라는 사용자 지정 속성 `Number.AccountId`를 정의합니다.

```
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) ]

이 예제에서는 초기화되지 않은 10바이트 어레이의 값을 사용하여 `ApplicationIcon`이라는 사용자 지정 속성 `Binary.JPEG`를 정의합니다.

```
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) 대기열로 메시지를 보내는 경우 메시지 그룹 ID를 제공한 **후 `sendMessage` 메서드가 실행되는지 확인하세요.  
`[SendMessage](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessage.html)` 대신 `[SendMessageBatch](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SendMessageBatch.html)` 메서드를 사용하는 경우 배치의 개별 메시지에 대해 메시지 속성을 지정해야 합니다.