

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

# Amazon SNS 주제 생성 및 메시지 게시
<a name="sns-getting-started"></a>

이 주제에서는 특히 주제, 구독 및 메시지 게시에 중점을 두고 Amazon SNS 리소스를 관리하기 위한 기본 단계를 제공합니다. 먼저 Amazon SNS에 필요한 액세스 권한을 설정하여 Amazon SNS 리소스를 생성하고 관리할 수 있는 올바른 권한이 있는지 확인합니다. 다음으로 구독자에게 메시지를 관리하고 전달하는 중앙 허브 역할을 하는 새 Amazon SNS 주제를 생성합니다. 주제를 생성한 후 이 주제에 대한 구독을 생성하여 특정 엔드포인트가 게시된 메시지를 수신할 수 있도록 합니다.

주제와 구독이 준비되면 Amazon SNS가 구독한 모든 엔드포인트에 메시지를 효율적으로 전달하는 방법을 관찰하면서 주제에 메시지를 게시합니다. 마지막으로 구독과 주제를 모두 삭제하고 관리한 Amazon SNS 리소스의 수명 주기를 완료하는 방법을 알아봅니다. 이 접근 방식은 Amazon SNS 콘솔을 사용하여 메시징 워크플로를 관리하는 데 필요한 실용적인 기술을 갖추도록 Amazon SNS 의 기본 작업에 대한 명확한 이해를 제공합니다.

# Amazon SNS에 대한 액세스 설정
<a name="sns-setting-up"></a>

Amazon SNS를 처음 사용하려면 먼저 다음 단계를 완료해야 합니다.

## AWS 계정 및 IAM 사용자 생성
<a name="create-aws-account"></a>

 AWS 서비스에 액세스하려면 먼저를 생성해야 합니다[AWS 계정](https://aws.amazon.com/). AWS 계정 를 사용하여 활동 및 사용 보고서를 보고 인증 및 액세스를 관리할 수 있습니다.

### 에 가입 AWS 계정
<a name="sign-up-for-aws"></a>

이 없는 경우 다음 단계를 AWS 계정완료하여 생성합니다.

**에 가입하려면 AWS 계정**

1. [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup)을 엽니다.

1. 온라인 지침을 따릅니다.

   등록 절차 중 전화 또는 텍스트 메시지를 받고 전화 키패드로 확인 코드를 입력하는 과정이 있습니다.

   에 가입하면 AWS 계정*AWS 계정 루트 사용자가* 생성됩니다. 루트 사용자에게는 계정의 모든 AWS 서비스 및 리소스에 액세스할 권한이 있습니다. 보안 모범 사례는 사용자에게 관리 액세스 권한을 할당하고, 루트 사용자만 사용하여 [루트 사용자 액세스 권한이 필요한 작업](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks)을 수행하는 것입니다.

AWS 는 가입 프로세스가 완료된 후 확인 이메일을 보냅니다. 언제든지 [https://aws.amazon.com/](https://aws.amazon.com/)으로 이동하고 **내 계정**을 선택하여 현재 계정 활동을 확인하고 계정을 관리할 수 있습니다.

### 관리자 액세스 권한이 있는 사용자 생성
<a name="create-an-admin"></a>

에 가입한 후 일상적인 작업에 AWS 계정 루트 사용자를 사용하지 않도록 루트 사용자를 AWS 계정보호하고, 활성화하고 AWS IAM Identity Center, 관리 사용자를 생성합니다.

**AWS 계정 루트 사용자 보안**

1.  **루트 사용자를** 선택하고 AWS 계정 이메일 주소를 입력하여 계정 소유자[AWS Management Console](https://console.aws.amazon.com/)로에 로그인합니다. 다음 페이지에서 비밀번호를 입력합니다.

   루트 사용자를 사용하여 로그인하는 데 도움이 필요하면 *AWS Sign-In 사용 설명서*의 [루트 사용자로 로그인](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial)을 참조하세요.

1. 루트 사용자의 다중 인증(MFA)을 활성화합니다.

   지침은 *IAM 사용 설명서*의 [AWS 계정 루트 사용자(콘솔)에 대한 가상 MFA 디바이스 활성화를 참조하세요](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html).

**관리자 액세스 권한이 있는 사용자 생성**

1. IAM Identity Center를 활성화합니다.

   지침은 *AWS IAM Identity Center 사용자 안내서*의 [AWS IAM Identity Center설정](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-set-up-for-idc.html)을 참조하세요.

1. IAM Identity Center에서 사용자에게 관리 액세스 권한을 부여합니다.

   를 자격 증명 소스 IAM Identity Center 디렉터리 로 사용하는 방법에 대한 자습서는 사용 *AWS IAM Identity Center 설명서*[의 기본값으로 사용자 액세스 구성을 IAM Identity Center 디렉터리](https://docs.aws.amazon.com//singlesignon/latest/userguide/quick-start-default-idc.html) 참조하세요.

**관리 액세스 권한이 있는 사용자로 로그인**
+ IAM IDentity Center 사용자로 로그인하려면 IAM Identity Center 사용자를 생성할 때 이메일 주소로 전송된 로그인 URL을 사용합니다.

  IAM Identity Center 사용자를 사용하여 로그인하는 데 도움이 필요하면 *AWS Sign-In 사용 설명서*[의 AWS 액세스 포털에 로그인](https://docs.aws.amazon.com/signin/latest/userguide/iam-id-center-sign-in-tutorial.html)을 참조하세요.

**추가 사용자에게 액세스 권한 할당**

1. IAM Identity Center에서 최소 권한 적용 모범 사례를 따르는 권한 세트를 생성합니다.

   지침은 [Create a permission set](https://docs.aws.amazon.com//singlesignon/latest/userguide/get-started-create-a-permission-set.html)에 대한 지침은 *AWS IAM Identity Center 사용 설명서*에서 참조하세요.

1. 사용자를 그룹에 할당하고, 그룹에 Single Sign-On 액세스 권한을 할당합니다.

   지침은 *AWS IAM Identity Center 사용 설명서*의 [Add groups](https://docs.aws.amazon.com//singlesignon/latest/userguide/addgroups.html)를 참조하세요.

## 다음 단계
<a name="next-steps-setting-up"></a>

이제 Amazon SNS로 작업할 준비가 되었으므로 다음과 같이 시작합니다.

1. [Amazon SNS 주제 생성](sns-create-topic.md)

1. [Amazon SNS 주제에서 구독 만들기](sns-create-subscribe-endpoint-to-topic.md) 

1. [Amazon SNS 메시지 게시](sns-publishing.md)

1. [Amazon SNS 주제 및 구독 삭제](sns-delete-subscription-topic.md)

# Amazon SNS 주제 생성
<a name="sns-create-topic"></a>

Amazon SNS 주제는 *커뮤니케이션 채널* 역할을 하는 논리적 액세스 포인트입니다. 주제를 사용하면 여러 *엔드포인트*(예: Amazon SQS AWS Lambda, HTTP/S 또는 이메일 주소)를 그룹화할 수 있습니다.

해당 메시지를 필요로 하는 다른 여러 시스템과 연동하는 메시지 생산자 시스템(예: 전자 상거래 웹 사이트)의 메시지를 브로드캐스트하기 위해 생산자 시스템에 대해 주제를 생성할 수 있습니다.

가장 먼저 이루어지고 가장 흔한 Amazon SNS 태스크는 주제를 생성하는 것입니다. 이 페이지에서는 AWS Management Console, AWS SDK for Java및를 사용하여 주제를 AWS SDK for .NET 생성하는 방법을 보여줍니다.

주제가 생성되는 동안 주제 유형(표준 또는 FIFO)을 선택하고 주제의 이름을 지정합니다. 주제를 생성한 후에는 주제 유형이나 이름을 변경할 수 없습니다. 다른 모든 구성 선택 사항은 주제 생성 중에 선택할 수 있는 사항이며 나중에 편집할 수 있습니다.

**중요**  
개인 식별 정보(PII)나 기타 기밀 정보 또는 민감한 정보를 주제 이름에 추가하지 마세요. 주제 이름을 통해 CloudWatch Logs를 포함하여 다른 Amazon Web Services에 액세스할 수 있습니다. 주제 이름은 개인 데이터나 민감한 데이터에 사용하기 위한 것이 아닙니다.

## 를 사용하여 주제를 생성하려면 AWS Management Console
<a name="create-topic-aws-console"></a>

Amazon SNS에서 주제를 만들면 메시지 배포의 토대가 정립되어 여러 구독자에게 팬아웃할 수 있는 메시지를 게시할 수 있습니다. 이 단계는 주제의 유형, 암호화 설정, 액세스 정책을 구성하여 주제가 조직의 보안, 규정 준수 및 운영 요구 사항을 충족하도록 지원하므로 중요합니다.

1. [Amazon SNS 콘솔](https://console.aws.amazon.com/sns/home)에 로그인합니다.

1. 다음 중 하나를 수행하세요.
   +  AWS 계정 이전에에서 생성된 주제가 없는 경우 홈 페이지에서 Amazon SNS에 대한 설명을 읽어보세요.
   +  AWS 계정 이전에에서 주제를 생성한 경우 탐색 패널에서 **주제를** 선택합니다.

1. **주제** 페이지에서 **주제 생성**을 선택합니다.

1. **주제 생성** 페이지의 **세부 정보** 섹션에서 다음을 수행합니다.

   1. **유형**에서 주제 유형(**표준** 또는 **FIFO**을 선택합니다.

   1. 주제의 **이름**을 입력합니다. [FIFO 주제](sns-fifo-topics.md)의 경우 이름 끝에 **.fifo**를 추가합니다.

   1. (선택 사항) 주제의 **표시 이름**을 입력합니다.
**중요**  
이메일 엔드포인트를 구독할 때 Amazon SNS 주제 표시 이름과 보내는 이메일 주소(예: no-reply@sns.amazonaws.com)의 문자 수를 합친 것이 UTF-8 320자를 초과해서는 안 됩니다. Amazon SNS 주제의 표시 이름을 구성하기 전에 서드 파티 인코딩 도구를 사용하여 전송하는 주소의 길이를 확인할 수 있습니다.

   1. (선택 사항) FIFO 주제의 경우 **콘텐츠 기반 메시지 중복 제거**를 선택하여 기본 메시지 중복 제거를 활성화할 수 있습니다. 자세한 정보는 [FIFO 주제에 대한 Amazon SNS 메시지 중복 제거](fifo-message-dedup.md)에서 확인하세요.

1. (선택 사항) **암호화** 섹션을 확장하고 다음을 수행합니다. 자세한 내용은 [서버 측 암호화를 사용한 Amazon SNS 데이터 보안](sns-server-side-encryption.md) 단원을 참조하십시오.

   1. **암호화 활성**을 선택합니다.

   1.  AWS KMS 키를 지정합니다. 자세한 내용은 [주요 용어](sns-server-side-encryption.md#sse-key-terms) 단원을 참조하십시오.

      각 KMS 유형에 대해 **설명(Description)**, **계정(Account)**, **KMS ARN**이 표시됩니다.
**중요**  
해당 KMS의 소유자가 아니거나 `kms:ListAliases` 및 `kms:DescribeKey` 권한이 없는 계정으로 로그인하는 경우 Amazon SNS 콘솔에서 해당 KMS에 대한 정보를 볼 수 없습니다.  
KMS의 소유자에게 이 권한을 부여해 달라고 요청해야 합니다. 자세한 정보는 *AWS Key Management Service 개발자 안내서*의 [AWS KMS API 권한: 작업 및 리소스 참조](https://docs.aws.amazon.com/kms/latest/developerguide/kms-api-permissions-reference.html)를 참조하세요.
      + Amazon SNS용 AWS 관리형 KMS**(기본값) alias/aws/sns**가 기본적으로 선택됩니다.
**참고**  
다음 사항에 유의하세요:  
 AWS Management Console 를 사용하여 주제에 대한 Amazon SNS용 AWS 관리형 KMS를 처음 지정하면가 Amazon SNS용 AWS 관리형 KMS를 AWS KMS 생성합니다.
또는 SSE가 활성화된 주제에 대해 `Publish` 작업을 처음 사용할 때가 Amazon SNS용 AWS 관리형 KMS를 AWS KMS 생성합니다.
      +  AWS 계정에서 사용자 지정 KMS를 사용하려면 **KMS 키** 필드를 선택한 다음 목록에서 사용자 지정 KMS를 선택합니다.
**참고**  
사용자 지정 KMS 생성에 대한 지침은 *AWS Key Management Service 개발자 안내서*의 [키 생성](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html)을 참조하세요.
      + 계정 또는 다른 AWS 계정의 사용자 지정 KMS ARN을 사용하려면 **KMS 키** 필드에 AWS 입력합니다.

1. (선택 사항) 기본적으로 주제 소유자만 주제에 게시하거나 주제를 구독할 수 있습니다. 추가 액세스 권한을 구성하려면 **액세스 정책** 섹션을 확장합니다. 자세한 내용은 [Amazon SNS의 Identity and Access Management](security-iam.md) 및 [Amazon SNS 액세스 제어의 예제 사례](sns-access-policy-use-cases.md) 섹션을 참조하세요.
**참고**  
콘솔을 사용하여 주제를 생성하는 경우 기본 정책은 `aws:SourceOwner` 조건 키를 사용합니다. 이 키는 `aws:SourceAccount`와 비슷합니다.

1. (선택 사항) Amazon SNS가 실패한 메시지 전송을 재시도하는 방식을 구성하려면 **전송 재시도 정책(HTTP/S)** 섹션을 확장합니다. 자세한 내용은 [Amazon SNS 메시지 전송 재시도](sns-message-delivery-retries.md) 단원을 참조하십시오.

1. (선택 사항) Amazon SNS가 CloudWatch로의 메시지 전송을 로깅하는 방식을 구성하려면 **전송 상태 로깅** 섹션을 확장합니다. 자세한 내용은 [Amazon SNS 메시지 전송 상태](sns-topic-attributes.md) 단원을 참조하십시오.

1. (선택 사항) 메타데이터 태그를 주제에 추가하려면 **태그** 섹션을 확장하고, **키**와 **값**(옵션)을 입력한 다음 **태그 추가**를 선택합니다. 자세한 내용은 [Amazon SNS 주제 태그 지정](sns-tags.md) 단원을 참조하십시오.

1. **주제 생성**을 선택합니다.

   주제가 생성되고 ***MyTopic*** 페이지가 표시됩니다.

   주제의 **이름**, **ARN**, (선택 사항) **표시 이름** 및 **주제 소유자**의 AWS 계정 ID가 **세부 정보** 섹션에 표시됩니다.

1. 다음 예와 같이 주제 ARN을 클립보드에 복사합니다.

   ```
   arn:aws:sns:us-east-2:123456789012:MyTopic
   ```

## AWS SDK를 사용하여 주제를 생성하려면
<a name="create-topic-aws-sdks"></a>

 AWS SDK를 사용하려면 자격 증명으로 구성해야 합니다. [자세한 정보는 *AWS SDK 및 도구 참조 가이드*의 공유 구성 및 자격 증명 파일](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)을 참조하세요.

다음 코드 예시는 `CreateTopic`의 사용 방법을 보여 줍니다.

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
특정 이름으로 주제를 생성합니다.  

```
    using System;
    using System.Threading.Tasks;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    /// <summary>
    /// This example shows how to use Amazon Simple Notification Service
    /// (Amazon SNS) to add a new Amazon SNS topic.
    /// </summary>
    public class CreateSNSTopic
    {
        public static async Task Main()
        {
            string topicName = "ExampleSNSTopic";

            IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();

            var topicArn = await CreateSNSTopicAsync(client, topicName);
            Console.WriteLine($"New topic ARN: {topicArn}");
        }

        /// <summary>
        /// Creates a new SNS topic using the supplied topic name.
        /// </summary>
        /// <param name="client">The initialized SNS client object used to
        /// create the new topic.</param>
        /// <param name="topicName">A string representing the topic name.</param>
        /// <returns>The Amazon Resource Name (ARN) of the created topic.</returns>
        public static async Task<string> CreateSNSTopicAsync(IAmazonSimpleNotificationService client, string topicName)
        {
            var request = new CreateTopicRequest
            {
                Name = topicName,
            };

            var response = await client.CreateTopicAsync(request);

            return response.TopicArn;
        }
    }
```
이름과 특정 FIFO 및 중복 제거 속성을 사용하여 새 주제를 생성합니다.  

```
    /// <summary>
    /// 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;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [CreateTopic](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/CreateTopic)을 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Create an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
  \param topicName: An Amazon SNS topic name.
  \param topicARNResult: String to return the Amazon Resource Name (ARN) for the topic.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::createTopic(const Aws::String &topicName,
                              Aws::String &topicARNResult,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::CreateTopicRequest request;
    request.SetName(topicName);

    const Aws::SNS::Model::CreateTopicOutcome outcome = snsClient.CreateTopic(request);

    if (outcome.IsSuccess()) {
        topicARNResult = outcome.GetResult().GetTopicArn();
        std::cout << "Successfully created an Amazon SNS topic " << topicName
                  << " with topic ARN '" << topicARNResult
                  << "'." << std::endl;

    }
    else {
        std::cerr << "Error creating topic " << topicName << ":" <<
                  outcome.GetError().GetMessage() << std::endl;
        topicARNResult.clear();
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [CreateTopic](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/CreateTopic)을 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**SNS 주제를 생성하려면**  
다음 `create-topic`예제에서는 `my-topic`이라는 SNS 주제를 생성합니다.  

```
aws sns create-topic \
    --name my-topic
```
출력:  

```
{
    "ResponseMetadata": {
        "RequestId": "1469e8d7-1642-564e-b85d-a19b4b341f83"
    },
    "TopicArn": "arn:aws:sns:us-west-2:123456789012:my-topic"
}
```
자세한 내용은 [AWS 명령줄 인터페이스 사용 설명서의 Amazon SQS 및 Amazon SNS](https://docs.aws.amazon.com/cli/latest/userguide/cli-sqs-queue-sns-topic.html)에서 명령줄 인터페이스 사용을 참조하세요. *AWS *   
+  API 세부 정보는 *AWS CLI 명령 참조*의 [CreateTopic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/create-topic.html)을 참조하세요.

------
#### [ Go ]

**SDK for Go V2**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
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"
	}
	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
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [CreateTopic](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.CreateTopic)을 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
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.SnsException;

/**
 * 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 CreateTopic {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <topicName>

                Where:
                   topicName - The name of the topic to create (for example, mytopic).

                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicName = args[0];
        System.out.println("Creating a topic with name: " + topicName);
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        String arnVal = createSNSTopic(snsClient, topicName);
        System.out.println("The topic ARN is" + arnVal);
        snsClient.close();
    }

    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 "";
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [CreateTopic](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/CreateTopic)을 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
별도의 모듈에서 클라이언트를 생성하고 내보냅니다.  

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```
SDK 및 클라이언트 모듈을 가져오고 API를 호출합니다.  

```
import { CreateTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicName - The name of the topic to create.
 */
export const createTopic = async (topicName = "TOPIC_NAME") => {
  const response = await snsClient.send(
    new CreateTopicCommand({ Name: topicName }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME'
  // }
  return response;
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topics-createtopic)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [CreateTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/CreateTopicCommand)을 참조하세요.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun createSNSTopic(topicName: String): String {
    val request =
        CreateTopicRequest {
            name = topicName
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.createTopic(request)
        return result.topicArn.toString()
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [CreateTopic](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PHP ]

**SDK for PHP**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Create a Simple Notification Service topics in your AWS account at the requested region.
 *
 * This code expects that you have AWS credentials set up per:
 * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html
 */

$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$topicname = 'myTopic';

try {
    $result = $SnSclient->createTopic([
        'Name' => $topicname,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  자세한 정보는 [AWS SDK for PHP 개발자 안내서](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-managing-topics.html#create-a-topic)를 참조하세요.
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [CreateTopic](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/CreateTopic)을 참조하세요.

------
#### [ Python ]

**SDK for Python (Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class SnsWrapper:
    """Encapsulates Amazon SNS topic and subscription functions."""

    def __init__(self, sns_resource):
        """
        :param sns_resource: A Boto3 Amazon SNS resource.
        """
        self.sns_resource = sns_resource


    def create_topic(self, name):
        """
        Creates a notification topic.

        :param name: The name of the topic to create.
        :return: The newly created topic.
        """
        try:
            topic = self.sns_resource.create_topic(Name=name)
            logger.info("Created topic %s with ARN %s.", name, topic.arn)
        except ClientError:
            logger.exception("Couldn't create topic %s.", name)
            raise
        else:
            return topic
```

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def create_topic(
        self, 
        topic_name: str, 
        is_fifo: bool = False, 
        content_based_deduplication: bool = False
    ) -> str:
        """
        Create an SNS topic.

        :param topic_name: The name of the topic to create.
        :param is_fifo: Whether to create a FIFO topic.
        :param content_based_deduplication: Whether to use content-based deduplication for FIFO topics.
        :return: The ARN of the created topic.
        :raises ClientError: If the topic creation fails.
        """
        try:
            # Add .fifo suffix for FIFO topics
            if is_fifo and not topic_name.endswith('.fifo'):
                topic_name += '.fifo'

            attributes = {}
            if is_fifo:
                attributes['FifoTopic'] = 'true'
                if content_based_deduplication:
                    attributes['ContentBasedDeduplication'] = 'true'

            response = self.sns_client.create_topic(
                Name=topic_name,
                Attributes=attributes
            )

            topic_arn = response['TopicArn']
            logger.info(f"Created topic: {topic_name} with ARN: {topic_arn}")
            return topic_arn

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error creating topic {topic_name}: {error_code} - {e}")
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [CreateTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/CreateTopic)를 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
# This class demonstrates how to create an Amazon Simple Notification Service (SNS) topic.
class SNSTopicCreator
  # Initializes an SNS client.
  #
  # Utilizes the default AWS configuration for region and credentials.
  def initialize
    @sns_client = Aws::SNS::Client.new
  end

  # Attempts to create an SNS topic with the specified name.
  #
  # @param topic_name [String] The name of the SNS topic to create.
  # @return [Boolean] true if the topic was successfully created, false otherwise.
  def create_topic(topic_name)
    @sns_client.create_topic(name: topic_name)
    puts "The topic '#{topic_name}' was successfully created."
    true
  rescue Aws::SNS::Errors::ServiceError => e
    # Handles SNS service errors gracefully.
    puts "Error while creating the topic named '#{topic_name}': #{e.message}"
    false
  end
end

# Example usage:
if $PROGRAM_NAME == __FILE__
  topic_name = 'YourTopicName' # Replace with your topic name
  sns_topic_creator = SNSTopicCreator.new

  puts "Creating the topic '#{topic_name}'..."
  unless sns_topic_creator.create_topic(topic_name)
    puts 'The topic was not created. Stopping program.'
    exit 1
  end
end
```
+  자세한 정보는 [AWS SDK for Ruby 개발자 안내서](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-create-topic.html)를 참조하세요.
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [CreateTopic](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/CreateTopic)을 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
async fn make_topic(client: &Client, topic_name: &str) -> Result<(), Error> {
    let resp = client.create_topic().name(topic_name).send().await?;

    println!(
        "Created topic with ARN: {}",
        resp.topic_arn().unwrap_or_default()
    );

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [CreateTopic](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.create_topic)을 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_sns->createtopic( iv_name = iv_topic_name ). " oo_result is returned for testing purposes. "
        MESSAGE 'SNS 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.
```
+  API에 대한 세부 정보는 *SAP ABAP용AWS SDK API 참조*의 [CreateTopic](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        let output = try await snsClient.createTopic(
            input: CreateTopicInput(name: name)
        )

        guard let arn = output.topicArn else {
            print("No topic ARN returned by Amazon SNS.")
            return
        }
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [CreateTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/createtopic(input:)) 섹션을 참조하세요.

------

# Amazon SNS 주제에서 구독 만들기
<a name="sns-create-subscribe-endpoint-to-topic"></a>

[주제](sns-create-topic.md)에 게시된 메시지를 수신하려면 [엔드포인트](#sns-endpoints)에서 해당 주제를 *구독*해야 합니다. 엔드포인트에서 주제를 구독하면 엔드포인트는 연결된 주제에 게시된 메시지를 수신하기 시작합니다.

**참고**  
HTTP(S) 엔드포인트, 이메일 주소 및 다른 AWS 계정 의 AWS 리소스는 메시지를 수신하기 전에 구독 확인이 필요합니다.

## 엔드포인트에서 Amazon SNS 주제를 구독하려면
<a name="subscribe-topic-aws-console"></a>

엔드포인트가 Amazon SNS 주제를 구독하면 지정된 엔드포인트로 메시지를 전송할 수 있으므로 메시지가 주제에 게시될 때 적절한 시스템에 알림이 전달되거나 사용자가 알림을 받을 수 있습니다. 이 단계는 주제를 애플리케이션, 이메일 수신자, 기타 서비스 등 소비자와 연결하여 시스템 간에 원활한 통신을 지원하는 데 필수적입니다.

1. [Amazon SNS 콘솔](https://console.aws.amazon.com/sns/home)에 로그인합니다.

1. 왼쪽의 탐색 창에서 **구독**을 선택합니다.

1. **구독** 페이지에서 **구독 생성**을 선택합니다.

1. **구독 생성** 페이지의 **세부 정보** 섹션에서 다음을 수행합니다.

   1. **주제 ARN**에서 주제의 Amazon 리소스 이름(ARN)을 선택합니다. 이 값은와 같이 Amazon SNS 주제를 생성할 때 생성된 AWS ARN입니다`arn:aws:sns:us-east-2:123456789012:your_topic`.

   1. **프로토콜**에서 엔드포인트 유형을 선택합니다.  사용 가능한 엔드포인트 유형은 다음과 같습니다.
      + [**HTTP/HTTPS**](sns-http-https-endpoint-as-subscriber.md)
      + [**Email/Email-JSON**](sns-email-notifications.md)
      + [****](sns-firehose-as-subscriber.md)
      + [** Amazon SQS**](sns-sqs-as-subscriber.md)
**참고**  
[SNS FIFO 주제](sns-fifo-topics.md)를 구독하려면 이 옵션을 선택합니다.
      + [**AWS Lambda**](sns-lambda-as-subscriber.md)
      + [**플랫폼 애플리케이션 엔드포인트**](sns-mobile-application-as-subscriber.md)
      + [**SMS**](sns-mobile-phone-number-as-subscriber.md) 

   1. **엔드포인트**에 이메일 주소 또는 Amazon SQS 대기열의 ARN과 같은 엔드포인트 값을 입력합니다.

   1. Firehose 엔드포인트만 해당: **구독 역할 ARN**에서 Firehose 전송 스트림에 쓰기 위해 만든 IAM 역할의 ARN을 지정합니다. 자세한 내용은 [Firehose 전송 스트림에서 Amazon SNS 주제를 구독하기 위한 사전 조건](prereqs-kinesis-data-firehose.md) 섹션을 참조하세요.

   1. (선택 사항) Firehose, Amazon SQS, HTTP/S 엔드포인트의 경우 원시 메시지 전송을 사용할 수도 있습니다. 자세한 내용은 [Amazon SNS 원시 메시지 전송](sns-large-payload-raw-message-delivery.md) 섹션을 참조하세요.

   1. (선택 사항) 필터 정책을 구성하려면 **구독 필터 정책** 섹션을 확장합니다. 자세한 내용은 [Amazon SNS 구독 필터 정책](sns-subscription-filter-policies.md) 섹션을 참조하세요.

   1. (선택 사항) 페이로드 기반 필터링을 활성화하려면 `Filter Policy Scope`를 `MessageBody`로 구성하세요. 자세한 내용은 [Amazon SNS 구독 필터 정책 범위](sns-message-filtering-scope.md) 섹션을 참조하세요.

   1. (선택 사항) 구독에 대한 배달 못한 편지 대기열을 구성하려면 **리드라이브 정책(배달 못한 편지 대기열)** 섹션을 확장합니다. 자세한 내용은 [Amazon SNS Dead Letter Queue(DLQ)](sns-dead-letter-queues.md) 섹션을 참조하세요.

   1. **구독 생성**을 선택합니다.

      콘솔에서 구독을 만들고 구독의 **세부 정보** 페이지를 엽니다.

# Amazon SNS 메시지 게시
<a name="sns-publishing"></a>

[Amazon SNS 주제를 생성](sns-create-topic.md)하고 엔드포인트에서 주제를 [구독 설정](sns-create-subscribe-endpoint-to-topic.md)한 후 주제에 메시지를 *게시*할 수 있습니다. 메시지가 게시되면 Amazon SNS는 구독 설정된 [엔드포인트](sns-create-subscribe-endpoint-to-topic.md#sns-endpoints)로 메시지를 전달하려고 시도합니다.

## 를 사용하여 Amazon SNS 주제에 메시지를 게시하려면 AWS Management Console
<a name="sns-publishing-messages"></a>

1. [Amazon SNS 콘솔](https://console.aws.amazon.com/sns/home)에 로그인합니다.

1. 왼쪽 탐색 창에서 **주제**를 선택합니다.

1. **주제** 페이지에서 주제를 선택하고 **메시지 게시**를 선택합니다.

   콘솔에서 **주제에 메시지 게시** 페이지가 열립니다.

1. **메시지 세부 정보** 섹션에서 다음을 수행합니다.

   1. (선택 사항) 메시지 **제목**을 입력합니다.

   1. [FIFO 주제](sns-fifo-topics.md)에 **메시지 그룹 ID**를 입력합니다. FIFO 주제에는 **메시지 그룹 ID**가 필요합니다. 동일한 메시지 그룹의 메시지는 게시된 순서대로 전송됩니다.

   1. (선택 사항) 표준 주제에 **메시지 그룹 ID**를 입력합니다. 이 ID는 모든 Amazon SQS 표준 구독에 전달되며 다른 엔드포인트 유형에 사용되거나 전송되지 않습니다.

   1. FIFO 주제에 **메시지 중복 제거 ID**를 입력합니다. 주제에 대해 **콘텐츠 기반 메시지 중복 제거** 설정을 사용하는 경우 이 ID는 선택 사항입니다.

   1. (선택 사항) [모바일 푸시 알림](sns-ttl.md)에 초 단위로 **유지 시간(TTL)**을 입력합니다. 이 시간은 Apple Push Notification Service(APNS) 또는 Firebase Cloud Messaging(FCM)과 같은 푸시 알림 서비스가 메시지를 엔드포인트에 전달해야 하는 시간입니다.

1. **메시지 본문** 섹션에서 다음 중 하나를 수행합니다.

   1. **모든 전송 프로토콜에 대해 동일한 페이로드**를 선택한 다음 메시지를 입력합니다.

   1. **각 전송 프로토콜에 대해 사용자 지정 페이로드**를 선택한 다음 JSON 객체를 입력하여 각 전송 프로토콜에 보낼 메시지를 정의합니다.

      자세한 내용은 [플랫폼별 페이로드를 사용하여 Amazon SNS 알림 게시](sns-send-custom-platform-specific-payloads-mobile-devices.md) 섹션을 참조하세요.

1. **메시지 속성** 섹션에서, Amazon SNS를 구독 속성인 `FilterPolicy`와 일치시켜 구독된 엔드포인트가 게시된 메시지와 관련이 있는지 확인하려는 속성을 추가합니다.

   1. **Type**에서 속성 유형(예:**String.Array**)을 선택합니다.
**참고**  
속성 유형 **String.Array**에 대해 배열을 대괄호로 묶습니다(`[]`). 배열 안에서는 문자열 값을 큰따옴표로 묶습니다. 숫자 또는 키워드 `true`, `false` 및 `null`에는 따옴표가 필요 없습니다.

   1. 속성 **Name**(예: `customer_interests`)을 입력합니다.

   1. 속성 **Value**(예: `["soccer", "rugby", "hockey"]`)를 입력합니다.

   속성 유형이 **String**, **String.Array** 또는 **Number**인 경우, 필터 정책 범위가 명시적으로 `MessageBody`로 설정되지 않았다면 Amazon SNS는 구독에 메시지를 전송하기 전에 구독의 [필터 정책](sns-message-filtering.md)(있는 경우)에 따라 메시지 속성을 평가합니다.

   자세한 내용은 [Amazon SNS 메시지 속성](sns-message-attributes.md) 섹션을 참조하세요.

1. **메시지 게시**를 선택합니다.

   메시지가 주제에 게시되고 콘솔에서 주제의 **세부 정보** 페이지가 열립니다.

## AWS SDK를 사용하여 주제에 메시지를 게시하려면
<a name="publish-to-topic-aws-sdks"></a>

 AWS SDK를 사용하려면 자격 증명으로 구성해야 합니다. [자세한 정보는 *AWS SDK 및 도구 참조 가이드*의 공유 구성 및 자격 증명 파일](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)을 참조하세요.

다음 코드 예시는 `Publish`의 사용 방법을 보여 줍니다.

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
주제에 메시지를 게시합니다.  

```
    using System;
    using System.Threading.Tasks;
    using Amazon.SimpleNotificationService;
    using Amazon.SimpleNotificationService.Model;

    /// <summary>
    /// This example publishes a message to an Amazon Simple Notification
    /// Service (Amazon SNS) topic.
    /// </summary>
    public class PublishToSNSTopic
    {
        public static async Task Main()
        {
            string topicArn = "arn:aws:sns:us-east-2:000000000000:ExampleSNSTopic";
            string messageText = "This is an example message to publish to the ExampleSNSTopic.";

            IAmazonSimpleNotificationService client = new AmazonSimpleNotificationServiceClient();

            await PublishToTopicAsync(client, topicArn, messageText);
        }

        /// <summary>
        /// Publishes a message to an Amazon SNS topic.
        /// </summary>
        /// <param name="client">The initialized client object used to publish
        /// to the Amazon SNS topic.</param>
        /// <param name="topicArn">The ARN of the topic.</param>
        /// <param name="messageText">The text of the message.</param>
        public static async Task PublishToTopicAsync(
            IAmazonSimpleNotificationService client,
            string topicArn,
            string messageText)
        {
            var request = new PublishRequest
            {
                TopicArn = topicArn,
                Message = messageText,
            };

            var response = await client.PublishAsync(request);

            Console.WriteLine($"Successfully published message ID: {response.MessageId}");
        }
    }
```
그룹, 복제, 속성 옵션을 사용하여 주제에 메시지를 게시하세요.  

```
    /// <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.");
                    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>
    /// 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,
        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;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [Publish](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Publish)를 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Send a message to an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
  \param message: The message to publish.
  \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::publishToTopic(const Aws::String &message,
                                 const Aws::String &topicARN,
                                 const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::PublishRequest request;
    request.SetMessage(message);
    request.SetTopicArn(topicARN);

    const Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request);

    if (outcome.IsSuccess()) {
        std::cout << "Message published successfully with id '"
                  << outcome.GetResult().GetMessageId() << "'." << std::endl;
    }
    else {
        std::cerr << "Error while publishing message "
                  << outcome.GetError().GetMessage()
                  << std::endl;
    }

    return outcome.IsSuccess();
}
```
속성을 사용하여 메시지 게시  

```
        static const Aws::String TONE_ATTRIBUTE("tone");
        static const Aws::Vector<Aws::String> TONES = {"cheerful", "funny", "serious",
                                                       "sincere"};

        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::SNS::SNSClient snsClient(clientConfiguration);

        Aws::SNS::Model::PublishRequest request;
        request.SetTopicArn(topicARN);
        Aws::String message = askQuestion("Enter a message text to publish.  ");
        request.SetMessage(message);

        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;

            cleanUp(topicARN,
                    queueURLS,
                    subscriptionARNS,
                    snsClient,
                    sqsClient);

            return false;
        }
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [Publish](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Publish)를 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**예제 1: 주제에 메시지를 게시하려면**  
다음 `publish`예제에서는 지정된 Amazon SNS 주제에 지정된 메시지를 게시합니다. 메시지는 줄 바꿈을 포함할 수 있는 텍스트 파일에서 제공됩니다.  

```
aws sns publish \
    --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" \
    --message file://message.txt
```
`message.txt`의 콘텐츠:  

```
Hello World
Second Line
```
출력:  

```
{
    "MessageId": "123a45b6-7890-12c3-45d6-111122223333"
}
```
**예제 2: 전화번호에 SMS 메시지를 게시하려면**  
다음 `publish`예제에서는 `Hello world!`메시지를 전화번호 `+1-555-555-0100`에 게시합니다.  

```
aws sns publish \
    --message "Hello world!" \
    --phone-number +1-555-555-0100
```
출력:  

```
{
    "MessageId": "123a45b6-7890-12c3-45d6-333322221111"
}
```
+  API 세부 정보는 *AWS CLI 명령 참조*의 [Publish](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/publish.html)를 참조하세요.

------
#### [ Go ]

**SDK for Go V2**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
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
}



// 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{
			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
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [Publish](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.Publish)를 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;
import software.amazon.awssdk.services.sns.model.SnsException;

/**
 * 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 PublishTopic {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <message> <topicArn>

                Where:
                   message - The message text to send.
                   topicArn - The ARN of the topic to publish.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String message = args[0];
        String topicArn = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        pubTopic(snsClient, message, topicArn);
        snsClient.close();
    }

    public static void pubTopic(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);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [Publish](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Publish)를 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
별도의 모듈에서 클라이언트를 생성하고 내보냅니다.  

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```
SDK 및 클라이언트 모듈을 가져오고 API를 호출합니다.  

```
import { PublishCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object
 *                                                 if you are using the `json` `MessageStructure`.
 * @param {string} topicArn - The ARN of the topic to which you would like to publish.
 */
export const publish = async (
  message = "Hello from SNS!",
  topicArn = "TOPIC_ARN",
) => {
  const response = await snsClient.send(
    new PublishCommand({
      Message: message,
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'e7f77526-e295-5325-9ee4-281a43ad1f05',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```
그룹, 복제, 속성 옵션을 사용하여 주제에 메시지를 게시하세요.  

```
  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
          ? {
              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();
    }
  }
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-publishing-messages.html)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [Publish](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/PublishCommand)를 참조하세요.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun pubTopic(
    topicArnVal: String,
    messageVal: String,
) {
    val request =
        PublishRequest {
            message = messageVal
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.publish(request)
        println("${result.messageId} message sent.")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [Publish](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PHP ]

**SDK for PHP**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Sends a message to an Amazon SNS topic.
 *
 * This code expects that you have AWS credentials set up per:
 * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html
 */

$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$message = 'This message is sent from a Amazon SNS code sample.';
$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->publish([
        'Message' => $message,
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  자세한 정보는 [AWS SDK for PHP 개발자 안내서](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-subscribing-unsubscribing-topics.html#publish-a-message-to-an-sns-topic)를 참조하세요.
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [Publish](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/Publish)를 참조하세요.

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**예제 1: 이 예제에서는 단일 MessageAttribute가 인라인으로 선언된 메시지를 게시하는 것을 보여줍니다.**  

```
Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute @{'City'=[Amazon.SimpleNotificationService.Model.MessageAttributeValue]@{DataType='String'; StringValue ='AnyCity'}}
```
**예제 2: 이 예제에서는 여러 MessageAttributes가 미리 선언된 메시지를 게시하는 것을 보여줍니다.**  

```
$cityAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute $messageAttributes
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V4)*의 [Publish](https://docs.aws.amazon.com/powershell/v4/reference)를 참조하세요.

**Tools for PowerShell V5**  
**예제 1: 이 예제에서는 단일 MessageAttribute가 인라인으로 선언된 메시지를 게시하는 것을 보여줍니다.**  

```
Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute @{'City'=[Amazon.SimpleNotificationService.Model.MessageAttributeValue]@{DataType='String'; StringValue ='AnyCity'}}
```
**예제 2: 이 예제에서는 여러 MessageAttributes가 미리 선언된 메시지를 게시하는 것을 보여줍니다.**  

```
$cityAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute $messageAttributes
```
+  API 세부 정보는 *AWS Tools for PowerShell Cmdlet 참조(V5)*의 [Publish](https://docs.aws.amazon.com/powershell/v5/reference)를 참조하세요.

------
#### [ Python ]

**SDK for Python(Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
구독이 속성을 기준으로 필터링할 수 있도록 속성이 포함된 메시지를 게시합니다.  

```
class SnsWrapper:
    """Encapsulates Amazon SNS topic and subscription functions."""

    def __init__(self, sns_resource):
        """
        :param sns_resource: A Boto3 Amazon SNS resource.
        """
        self.sns_resource = sns_resource


    @staticmethod
    def publish_message(topic, message, attributes):
        """
        Publishes a message, with attributes, to a topic. Subscriptions can be filtered
        based on message attributes so that a subscription receives messages only
        when specified attributes are present.

        :param topic: The topic to publish to.
        :param message: The message to publish.
        :param attributes: The key-value attributes to attach to the message. Values
                           must be either `str` or `bytes`.
        :return: The ID of the message.
        """
        try:
            att_dict = {}
            for key, value in attributes.items():
                if isinstance(value, str):
                    att_dict[key] = {"DataType": "String", "StringValue": value}
                elif isinstance(value, bytes):
                    att_dict[key] = {"DataType": "Binary", "BinaryValue": value}
            response = topic.publish(Message=message, MessageAttributes=att_dict)
            message_id = response["MessageId"]
            logger.info(
                "Published message with attributes %s to topic %s.",
                attributes,
                topic.arn,
            )
        except ClientError:
            logger.exception("Couldn't publish message to topic %s.", topic.arn)
            raise
        else:
            return message_id
```
구독자의 프로토콜에 따라 다른 양식을 사용하는 메시지를 게시합니다.  

```
class SnsWrapper:
    """Encapsulates Amazon SNS topic and subscription functions."""

    def __init__(self, sns_resource):
        """
        :param sns_resource: A Boto3 Amazon SNS resource.
        """
        self.sns_resource = sns_resource


    @staticmethod
    def publish_multi_message(
        topic, subject, default_message, sms_message, email_message
    ):
        """
        Publishes a multi-format message to a topic. A multi-format message takes
        different forms based on the protocol of the subscriber. For example,
        an SMS subscriber might receive a short version of the message
        while an email subscriber could receive a longer version.

        :param topic: The topic to publish to.
        :param subject: The subject of the message.
        :param default_message: The default version of the message. This version is
                                sent to subscribers that have protocols that are not
                                otherwise specified in the structured message.
        :param sms_message: The version of the message sent to SMS subscribers.
        :param email_message: The version of the message sent to email subscribers.
        :return: The ID of the message.
        """
        try:
            message = {
                "default": default_message,
                "sms": sms_message,
                "email": email_message,
            }
            response = topic.publish(
                Message=json.dumps(message), Subject=subject, MessageStructure="json"
            )
            message_id = response["MessageId"]
            logger.info("Published multi-format message to topic %s.", topic.arn)
        except ClientError:
            logger.exception("Couldn't publish message to topic %s.", topic.arn)
            raise
        else:
            return message_id
```

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def publish_message(
        self,
        topic_arn: str,
        message: str,
        tone_attribute: Optional[str] = None,
        deduplication_id: Optional[str] = None,
        message_group_id: Optional[str] = None
    ) -> str:
        """
        Publish a message to an SNS topic.

        :param topic_arn: The ARN of the SNS topic.
        :param message: The message content to publish.
        :param tone_attribute: Optional tone attribute for message filtering.
        :param deduplication_id: Optional deduplication ID for FIFO topics.
        :param message_group_id: Optional message group ID for FIFO topics.
        :return: The message ID of the published message.
        :raises ClientError: If the message publication fails.
        """
        try:
            publish_args = {
                'TopicArn': topic_arn,
                'Message': message
            }

            # Add message attributes if tone is specified
            if tone_attribute:
                publish_args['MessageAttributes'] = {
                    'tone': {
                        'DataType': 'String',
                        'StringValue': tone_attribute
                    }
                }

            # Add FIFO-specific parameters
            if message_group_id:
                publish_args['MessageGroupId'] = message_group_id

            if deduplication_id:
                publish_args['MessageDeduplicationId'] = deduplication_id

            response = self.sns_client.publish(**publish_args)

            message_id = response['MessageId']
            logger.info(f"Published message to topic {topic_arn} with ID: {message_id}")
            return message_id

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error publishing message to topic: {error_code} - {e}")
            raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [Publish](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Publish)를 참조하세요.

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
# Service class for sending messages using Amazon Simple Notification Service (SNS)
class SnsMessageSender
  # Initializes the SnsMessageSender with an SNS client
  #
  # @param sns_client [Aws::SNS::Client] The SNS client
  def initialize(sns_client)
    @sns_client = sns_client
    @logger = Logger.new($stdout)
  end

  # Sends a message to a specified SNS topic
  #
  # @param topic_arn [String] The ARN of the SNS topic
  # @param message [String] The message to send
  # @return [Boolean] true if message was successfully sent, false otherwise
  def send_message(topic_arn, message)
    @sns_client.publish(topic_arn: topic_arn, message: message)
    @logger.info("Message sent successfully to #{topic_arn}.")
    true
  rescue Aws::SNS::Errors::ServiceError => e
    @logger.error("Error while sending the message: #{e.message}")
    false
  end
end

# Example usage:
if $PROGRAM_NAME == __FILE__
  topic_arn = 'SNS_TOPIC_ARN' # Should be replaced with a real topic ARN
  message = 'MESSAGE'         # Should be replaced with the actual message content

  sns_client = Aws::SNS::Client.new
  message_sender = SnsMessageSender.new(sns_client)

  @logger.info('Sending message.')
  unless message_sender.send_message(topic_arn, message)
    @logger.error('Message sending failed. Stopping program.')
    exit 1
  end
end
```
+  자세한 정보는 [AWS SDK for Ruby 개발자 안내서](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-send-message.html)를 참조하세요.
+  API 세부 정보는 *AWS SDK for Ruby API 참조*의 [Publish](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/Publish)를 참조하세요.

------
#### [ Rust ]

**SDK for Rust**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
async fn subscribe_and_publish(
    client: &Client,
    topic_arn: &str,
    email_address: &str,
) -> Result<(), Error> {
    println!("Receiving on topic with ARN: `{}`", topic_arn);

    let rsp = client
        .subscribe()
        .topic_arn(topic_arn)
        .protocol("email")
        .endpoint(email_address)
        .send()
        .await?;

    println!("Added a subscription: {:?}", rsp);

    let rsp = client
        .publish()
        .topic_arn(topic_arn)
        .message("hello sns!")
        .send()
        .await?;

    println!("Published message: {:?}", rsp);

    Ok(())
}
```
+  API 세부 정보는 *AWS SDK for Rust API 참조*의 [Publish](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.publish)을 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_topicarn = iv_topic_arn
          iv_message = iv_message ).
        MESSAGE 'Message published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
속성이 포함된 메시지를 주제에 게시합니다.  

```
    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_topicarn = iv_topic_arn
          iv_message = iv_message
          it_messageattributes = it_msg_attrs ).
        MESSAGE 'Message with attributes published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
주제에 다중 형식 메시지를 게시합니다.  

```
    " Build JSON message structure for multi-format message
    DATA(lv_json_message) = |\{ "default": "{ iv_default_message }", "sms": "{ iv_sms_message }", "email": "{ iv_email_message }" \}|.

    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_topicarn = iv_topic_arn
          iv_message = lv_json_message
          iv_subject = iv_subject
          iv_messagestructure = 'json' ).
        MESSAGE 'Multi-format message published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *SAP ABAP용AWS SDK API 참조*의 [Publish](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)를 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        let output = try await snsClient.publish(
            input: PublishInput(
                message: message,
                topicArn: arn
            )
        )

        guard let messageId = output.messageId else {
            print("No message ID received from Amazon SNS.")
            return
        }
        
        print("Published message with ID \(messageId)")
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [Publish](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/publish(input:)) 섹션을 참조하세요.

------

# Amazon SNS 및 Amazon S3 S3를 사용하여 대용량 메시지 게시
<a name="large-message-payloads"></a>

대용량 Amazon SNS 메시지를 게시하려면 [Java용 Amazon SNS 확장 클라이언트 라이브러리](https://github.com/awslabs/amazon-sns-java-extended-client-lib/) 또는 [Python용 Amazon SNS 확장 클라이언트 라이브러리](https://github.com/awslabs/amazon-sns-python-extended-client-lib)를 사용할 수 있습니다. 이 라이브러리는 현재 최대값인 256KB(최대 2GB)보다 큰 메시지에 유용합니다. 모든 라이브러리는 실제 페이로드를 Amazon S3 버킷에 저장하고 저장된 Amazon S3 객체의 참조를 Amazon SNS 주제에 게시합니다. 구독한 Amazon SQS 대기열은 [Java용 Amazon SQS 확장 클라이언트 라이브러리](https://github.com/awslabs/amazon-sqs-java-extended-client-lib)를 사용하여 Amazon S3에서 페이로드를 역참조하고 검색할 수 있습니다. Lambda와 같은 다른 엔드포인트는 [AWS용 페이로드 오프로딩 Java 공통 라이브러리](https://github.com/awslabs/payload-offloading-java-common-lib-for-aws)를 사용하여 페이로드를 역참조 및 검색할 수 있습니다.

**참고**  
Amazon SNS 확장 클라이언트 라이브러리는 표준 및 FIFO 주제와 호환됩니다.

# Java용 Amazon SNS 확장 클라이언트 라이브러리
<a name="extended-client-library-java"></a>

## 사전 조건
<a name="prereqs-sns-extended-client-library"></a>

다음은 [Java용 Amazon SNS 확장 클라이언트 라이브러리](https://github.com/awslabs/amazon-sns-java-extended-client-lib) 사용을 위한 사전 조건입니다.
+  AWS SDK. 이 페이지의 예제에서는 AWS Java SDK를 사용합니다. SDK를 설치하고 설정하려면 *AWS SDK for Java 개발자 안내서*[의 Java용 AWS SDK 설정을](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-install.html) 참조하세요.
+ 적절한 자격 증명이 AWS 계정 있는 . 를 생성하려면 [AWS 홈 페이지로](https://aws.amazon.com/) AWS 계정이동한 다음 ** AWS 계정 생성을** 선택합니다. 지침을 따릅니다.

  자격 증명에 대한 자세한 내용은 *AWS SDK for Java 개발자 안내서*의 [개발을 위한 AWS 자격 증명 및 리전 설정을](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-credentials.html) 참조하세요.
+ Java 8 이상.
+ Java용 Amazon SNS 확장 클라이언트 라이브러리([Maven](https://maven.apache.org/)에서도 사용 가능).

## 메시지 스토리지 구성
<a name="large-message-configure-storage"></a>

Amazon SNS 확장 클라이언트 라이브러리는 메시지 저장 및 검색을 AWS 위해 용 페이로드 오프로딩 Java 공통 라이브러리를 사용합니다. 다음 Amazon S3 [메시지 스토리지 옵션](https://github.com/awslabs/amazon-sns-java-extended-client-lib/blob/main/src/main/java/software/amazon/sns/SNSExtendedClientConfiguration.java)을 구성할 수 있습니다.
+ **사용자 지정 메시지 크기 임곗값** – 페이로드 및 속성이 이 크기를 초과하는 메시지는 Amazon S3에 자동으로 저장됩니다.
+ **`alwaysThroughS3` 플래그** - 이 값을 `true`로 설정하여 모든 메시지 페이로드가 Amazon S3에 강제로 저장되도록 합니다. 예:

  ```
  SNSExtendedClientConfiguration snsExtendedClientConfiguration = new
  SNSExtendedClientConfiguration() .withPayloadSupportEnabled(s3Client, BUCKET_NAME).withAlwaysThroughS3(true);
  ```
+ **사용자 지정 KMS 키** – Amazon S3 버킷에서 서버 측 암호화에 사용할 키입니다.
+ **버킷 이름** - 메시지 페이로드를 저장하기 위한 Amazon S3 버킷의 이름입니다.

## 예: Amazon S3에 저장된 페이로드로 Amazon SNS에 메시지 게시
<a name="example-s3-large-payloads"></a>

다음 코드 예제에서는 다음과 같은 작업을 수행하는 방법을 보여줍니다.
+ 샘플 주제 및 대기열을 만듭니다.
+ 대기열에서 구독하여 주제의 메시지를 수신합니다.
+ 테스트 메시지를 게시합니다.

메시지 페이로드는 Amazon S3에 저장되고 이에 대한 참조가 게시됩니다. Amazon SQS 확장 클라이언트는 메시지를 수신하는 데 사용됩니다.

**Java 1.x용 SDK**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/java/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
대용량 메시지를 게시하려면 Java용 Amazon SNS 확장 클라이언트 라이브러리를 사용하세요. 보내는 메시지는 실제 메시지 내용이 포함된 Amazon S3 객체를 참조합니다.  

```
import com.amazon.sqs.javamessaging.AmazonSQSExtendedClient;
import com.amazon.sqs.javamessaging.ExtendedClientConfiguration;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.SetSubscriptionAttributesRequest;
import com.amazonaws.services.sns.util.Topics;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.ReceiveMessageResult;
import software.amazon.sns.AmazonSNSExtendedClient;
import software.amazon.sns.SNSExtendedClientConfiguration;

public class Example {

        public static void main(String[] args) {
                final String BUCKET_NAME = "extended-client-bucket";
                final String TOPIC_NAME = "extended-client-topic";
                final String QUEUE_NAME = "extended-client-queue";
                final Regions region = Regions.DEFAULT_REGION;

                // Message threshold controls the maximum message size that will be allowed to
                // be published
                // through SNS using the extended client. Payload of messages exceeding this
                // value will be stored in
                // S3. The default value of this parameter is 256 KB which is the maximum
                // message size in SNS (and SQS).
                final int EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD = 32;

                // Initialize SNS, SQS and S3 clients
                final AmazonSNS snsClient = AmazonSNSClientBuilder.standard().withRegion(region).build();
                final AmazonSQS sqsClient = AmazonSQSClientBuilder.standard().withRegion(region).build();
                final AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(region).build();

                // Create bucket, topic, queue and subscription
                s3Client.createBucket(BUCKET_NAME);
                final String topicArn = snsClient.createTopic(
                                new CreateTopicRequest().withName(TOPIC_NAME)).getTopicArn();
                final String queueUrl = sqsClient.createQueue(
                                new CreateQueueRequest().withQueueName(QUEUE_NAME)).getQueueUrl();
                final String subscriptionArn = Topics.subscribeQueue(
                                snsClient, sqsClient, topicArn, queueUrl);

                // To read message content stored in S3 transparently through SQS extended
                // client,
                // set the RawMessageDelivery subscription attribute to TRUE
                final SetSubscriptionAttributesRequest subscriptionAttributesRequest = new SetSubscriptionAttributesRequest();
                subscriptionAttributesRequest.setSubscriptionArn(subscriptionArn);
                subscriptionAttributesRequest.setAttributeName("RawMessageDelivery");
                subscriptionAttributesRequest.setAttributeValue("TRUE");
                snsClient.setSubscriptionAttributes(subscriptionAttributesRequest);

                // Initialize SNS extended client
                // PayloadSizeThreshold triggers message content storage in S3 when the
                // threshold is exceeded
                // To store all messages content in S3, use AlwaysThroughS3 flag
                final SNSExtendedClientConfiguration snsExtendedClientConfiguration = new SNSExtendedClientConfiguration()
                                .withPayloadSupportEnabled(s3Client, BUCKET_NAME)
                                .withPayloadSizeThreshold(EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD);
                final AmazonSNSExtendedClient snsExtendedClient = new AmazonSNSExtendedClient(snsClient,
                                snsExtendedClientConfiguration);

                // Publish message via SNS with storage in S3
                final String message = "This message is stored in S3 as it exceeds the threshold of 32 bytes set above.";
                snsExtendedClient.publish(topicArn, message);

                // Initialize SQS extended client
                final ExtendedClientConfiguration sqsExtendedClientConfiguration = new ExtendedClientConfiguration()
                                .withPayloadSupportEnabled(s3Client, BUCKET_NAME);
                final AmazonSQSExtendedClient sqsExtendedClient = new AmazonSQSExtendedClient(sqsClient,
                                sqsExtendedClientConfiguration);

                // Read the message from the queue
                final ReceiveMessageResult result = sqsExtendedClient.receiveMessage(queueUrl);
                System.out.println("Received message is " + result.getMessages().get(0).getBody());
        }
}
```

## 기타 엔드포인트 프로토콜
<a name="large-payloads-other-protocols"></a>

Amazon SNS 및 Amazon SQS 라이브러리는 모두 [AWS용 페이로드 오프로딩 Java 공통 라이브러리](https://github.com/awslabs/payload-offloading-java-common-lib-for-aws)를 사용하여 Amazon S3로 메시지 페이로드를 저장하고 검색합니다. 모든 Java 지원 엔드포인트(예: Java로 구현된 HTTPS 엔드포인트)는 동일한 라이브러리를 사용하여 메시지 콘텐츠를 역참조할 수 있습니다.

용 페이로드 오프로딩 Java 공통 라이브러리를 사용할 수 없는 엔드포인트는 여전히 Amazon S3에 저장된 페이로드가 있는 메시지를 게시할 AWS 수 있습니다. 다음은 위의 코드 예제에서 게시한 Amazon S3 참조의 예입니다.

```
[
  "software.amazon.payloadoffloading.PayloadS3Pointer",
  {
    "s3BucketName": "extended-client-bucket",
    "s3Key": "xxxx-xxxxx-xxxxx-xxxxxx"
  }
]
```

# Python용 Amazon SNS 확장 클라이언트 라이브러리
<a name="extended-client-library-python"></a>

## 사전 조건
<a name="prereqs-sns-extended-client-library-python"></a>

다음은 [Python용 Amazon SNS 확장 클라이언트 라이브러리](https://github.com/awslabs/amazon-sns-python-extended-client-lib) 사용을 위한 사전 조건입니다.
+  AWS SDK. 이 페이지의 예제에서는 AWS Python SDK Boto3를 사용합니다. SDK를 설치하고 설정하려면 [https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) 설명서를 참조하세요.
+ 적절한 자격 증명이 AWS 계정 있는 . 를 생성하려면 [AWS 홈 페이지로](https://aws.amazon.com/) AWS 계정이동한 다음 ** AWS 계정 생성을** 선택합니다. 지침을 따릅니다.

  자격 증명에 대한 자세한 내용은 *Python용AWS SDK 개발자 안내서*에서 [자격 증명](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html)을 참조하세요.
+ Python 3.x (또는 이후 버전) 및 pip.
+ Python용 Amazon SNS 확장 클라이언트 라이브러리([PyPI](https://pypi.org/project/amazon-sns-extended-client/)에서도 사용 가능).

## 메시지 스토리지 구성
<a name="large-message-configure-storage-python"></a>

아래 속성은 Boto3 Amazon SNS [클라이언트](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns.html#client), [주제](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns/topic/index.html) 및 [PlatformEndpoint](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns/platformendpoint/index.html) 객체에서 사용할 수 있어 Amazon S3 메시지 스토리지 옵션을 구성할 수 있습니다.
+ **`large_payload_support`** - 대용량 메시지를 저장하는 Amazon S3 버킷 이름입니다.
+ **`use_legacy_attribute`**: `True`인 경우 게시된 모든 메시지는 현재 예약된 메시지 속성(`ExtendedPayloadSize`) 대신 이전 예약 메시지 속성(`SQSLargePayloadSize`)을 사용합니다.
+ **`message_size_threshold`** — 대용량 메시지 버킷에 메시지를 저장하기 위한 임계값입니다. 값은 `0` 이하 또는 `262144` 이상이면 안 됩니다. 기본값은 `262144`입니다.
+ **`always_through_s3`** - `True`인 경우 모든 메시지가 Amazon S3에 저장됩니다. 기본값은 `False`입니다.
+ **`s3_client`** - Amazon S3에 `client` 객체를 저장하는 데 사용되는 Boto3 Amazon S3 객체입니다. Amazon S3 클라이언트(예: 사용자 지정 Amazon S3 구성 또는 자격 증명)를 제어하려면 이 옵션을 사용하세요. 처음 사용할 때 이전에 설정하지 않은 경우 기본값은 `boto3.client("s3")`입니다.

## 예: Amazon S3에 저장된 페이로드로 Amazon SNS에 메시지 게시
<a name="example-s3-large-payloads-python"></a>

다음 코드 예제에서는 다음과 같은 작업을 수행하는 방법을 보여줍니다.
+ 샘플 Amazon SNS 주제 및 Amazon SQS 대기열을 생성합니다.
+ 정책을 Amazon SQS 대기열에 연결하여 Amazon SNS 주제에서 메시지를 수신합니다.
+ 대기열에서 구독하여 주제의 메시지를 수신합니다.
+ Amazon SNS 확장 클라이언트, 주제 리소스 및 PlatformEndpoint 리소스를 사용하여 테스트 메시지를 게시합니다.
+ 메시지 페이로드는 Amazon S3에 저장되고 이에 대한 참조가 게시됩니다.
+ 대기열에 게시된 메시지를 Amazon S3에서 검색된 원본 메시지와 함께 인쇄합니다.

대용량 메시지를 게시하려면 Python용 Amazon SNS 확장 클라이언트 라이브러리를 사용하세요. 보내는 메시지는 실제 메시지 내용이 포함된 Amazon S3 객체를 참조합니다.

```
import boto3
from sns_extended_client import SNSExtendedClientSession
from json import loads

s3_extended_payload_bucket = "extended-client-bucket-store"  # S3 bucket with the given bucket name is a resource which is created and accessible with the given AWS credentials
TOPIC_NAME = "---TOPIC-NAME---"
QUEUE_NAME = "---QUEUE-NAME---"

def allow_sns_to_write_to_sqs(topicarn, queuearn):
    policy_document = """{{
        "Version": "2012-10-17",		 	 	 
        "Statement":[
            {{
            "Sid":"MyPolicy",
            "Effect":"Allow",
            "Principal" : {{"AWS" : "*"}},
            "Action":"SQS:SendMessage",
            "Resource": "{}",
            "Condition":{{
                "ArnEquals":{{
                "aws:SourceArn": "{}"
                }}
            }}
            }}
        ]
        }}""".format(queuearn, topicarn)

    return policy_document

def get_msg_from_s3(body,sns_extended_client):
    """Handy Helper to fetch message from S3"""
    json_msg = loads(body)
    s3_object = sns_extended_client.s3_client.get_object(
        Bucket=json_msg[1].get("s3BucketName"), Key=json_msg[1].get("s3Key")
    )
    msg = s3_object.get("Body").read().decode()
    return msg


def fetch_and_print_from_sqs(sqs, queue_url,sns_extended_client):
    sqs_msg = sqs.receive_message(
        QueueUrl=queue_url,
        AttributeNames=['All'],
        MessageAttributeNames=['All'],
        VisibilityTimeout=0,
        WaitTimeSeconds=0,
        MaxNumberOfMessages=1
    ).get("Messages")[0]
    
    message_body = sqs_msg.get("Body")
    print("Published Message: {}".format(message_body))
    print("Message Stored in S3 Bucket is: {}\n".format(get_msg_from_s3(message_body,sns_extended_client)))

    # Delete the Processed Message
    sqs.delete_message(
        QueueUrl=queue_url,
        ReceiptHandle=sqs_msg['ReceiptHandle']
    )


sns_extended_client = boto3.client("sns", region_name="us-east-1")
create_topic_response = sns_extended_client.create_topic(Name=TOPIC_NAME)
sns_topic_arn = create_topic_response.get("TopicArn")

# create and subscribe an sqs queue to the sns client
sqs = boto3.client("sqs",region_name="us-east-1")
demo_queue_url = sqs.create_queue(QueueName=QUEUE_NAME).get("QueueUrl")
sqs_queue_arn = sqs.get_queue_attributes(
    QueueUrl=demo_queue_url, AttributeNames=["QueueArn"]
)["Attributes"].get("QueueArn")

# Adding policy to SQS queue such that SNS topic can send msg to SQS queue
policy_json = allow_sns_to_write_to_sqs(sns_topic_arn, sqs_queue_arn)
response = sqs.set_queue_attributes(
    QueueUrl = demo_queue_url,
    Attributes = {
        'Policy' : policy_json
    }
)

# Set the RawMessageDelivery subscription attribute to TRUE if you want to use
# SQSExtendedClient to help with retrieving msg from S3
sns_extended_client.subscribe(TopicArn=sns_topic_arn, Protocol="sqs", 
Endpoint=sqs_queue_arn
, Attributes={"RawMessageDelivery":"true"}
)

sns_extended_client.large_payload_support = s3_extended_payload_bucket

# Change default s3_client attribute of sns_extended_client to use 'us-east-1' region
sns_extended_client.s3_client = boto3.client("s3", region_name="us-east-1")


# Below is the example that all the messages will be sent to the S3 bucket
sns_extended_client.always_through_s3 = True
sns_extended_client.publish(
    TopicArn=sns_topic_arn, Message="This message should be published to S3"
)
print("\n\nPublished using SNS extended client:")
fetch_and_print_from_sqs(sqs, demo_queue_url,sns_extended_client)  # Prints message stored in s3

# Below is the example that all the messages larger than 32 bytes will be sent to the S3 bucket
print("\nUsing decreased message size threshold:")

sns_extended_client.always_through_s3 = False
sns_extended_client.message_size_threshold = 32
sns_extended_client.publish(
    TopicArn=sns_topic_arn,
    Message="This message should be published to S3 as it exceeds the limit of the 32 bytes",
)

fetch_and_print_from_sqs(sqs, demo_queue_url,sns_extended_client)  # Prints message stored in s3


# Below is the example to publish message using the SNS.Topic resource
sns_extended_client_resource = SNSExtendedClientSession().resource(
    "sns", region_name="us-east-1"
)

topic = sns_extended_client_resource.Topic(sns_topic_arn)
topic.large_payload_support = s3_extended_payload_bucket

# Change default s3_client attribute of topic to use 'us-east-1' region
topic.s3_client = boto3.client("s3", region_name="us-east-1")

topic.always_through_s3 = True
# Can Set custom S3 Keys to be used to store objects in S3
topic.publish(
    Message="This message should be published to S3 using the topic resource",
    MessageAttributes={
        "S3Key": {
            "DataType": "String",
            "StringValue": "347c11c4-a22c-42e4-a6a2-9b5af5b76587",
        }
    },
)
print("\nPublished using Topic Resource:")
fetch_and_print_from_sqs(sqs, demo_queue_url,topic)

# Below is the example to publish message using the SNS.PlatformEndpoint resource
sns_extended_client_resource = SNSExtendedClientSession().resource(
    "sns", region_name="us-east-1"
)

platform_endpoint = sns_extended_client_resource.PlatformEndpoint(sns_topic_arn)
platform_endpoint.large_payload_support = s3_extended_payload_bucket

# Change default s3_client attribute of platform_endpoint to use 'us-east-1' region
platform_endpoint.s3_client = boto3.client("s3", region_name="us-east-1")

platform_endpoint.always_through_s3 = True
# Can Set custom S3 Keys to be used to store objects in S3
platform_endpoint.publish(
    Message="This message should be published to S3 using the PlatformEndpoint resource",
    MessageAttributes={
        "S3Key": {
            "DataType": "String",
            "StringValue": "247c11c4-a22c-42e4-a6a2-9b5af5b76587",
        }
    },
)
print("\nPublished using PlatformEndpoint Resource:")
fetch_and_print_from_sqs(sqs, demo_queue_url,platform_endpoint)
```

**출력**

```
Published using SNS extended client:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3

Using decreased message size threshold:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3 as it exceeds the limit of the 32 bytes

Published using Topic Resource:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3 using the topic resource

Published using PlatformEndpoint Resource:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3 using the PlatformEndpoint resource
```

# Amazon SNS 메시지 속성
<a name="sns-message-attributes"></a>

Amazon SNS는 메시지에 대한 구조적 메타데이터 항목(예: 타임스탬프, 지형 정보 데이터, 서명 및 식별자)을 제공하도록 해주는 메시지 속성의 전송을 지원합니다. SQS 구독의 경우 [원시 메시지 전송](sns-large-payload-raw-message-delivery.md)이 사용된다면 최대 10개의 메시지 속성을 보낼 수 있습니다. 10개가 넘는 메시지 속성을 보내려면 원시 메시지 전송을 사용 중지해야 합니다. 원시 메시지 전송이 활성화된 Amazon SQS 구독으로 전달되는 메시지 속성이 10개를 초과하는 메시지는 클라이언트 측 오류로 삭제됩니다.

메시지 속성은 선택 사항이며 메시지 본문과 분리되지만 함께 전송됩니다. 수신자는 이 정보를 사용하여 메시지 본문을 먼저 처리할 필요 없이 메시지를 처리하는 방법을 결정할 수 있습니다.

 AWS Management Console 또는를 사용하여 속성이 있는 메시지를 보내는 방법에 대한 자세한 내용은 [를 사용하여 Amazon SNS 주제에 메시지를 게시하려면 AWS Management Console](sns-publishing.md#sns-publishing-messages) 자습서를 AWS SDK for Java참조하세요.

**참고**  
메시지 구조가 문자열이고 JSON이 아닌 경우에만 메시지 속성이 전송됩니다.

메시지 속성을 사용하여 모바일 엔드포인트에 대한 푸시 알림 메시지를 구성할 수도 있습니다. 이 시나리오에서 메시지 속성은 푸시 알림 메시지를 구성하는 데만 사용됩니다. 이 속성은 메시지 속성이 있는 메시지를 Amazon SQS 엔드포인트에 전송할 때와 같이 엔드포인트에 제공되지 않습니다.

메시지 속성을 사용하여 구독 필터 정책으로 메시지를 필터링할 수 있도록 만들 수 있습니다. 주제 구독에 필터 정책을 적용할 수 있습니다. `MessageAttributes`(기본)로 설정된 필터 정책 범위로 필터 정책이 적용되면 구독은 정책이 수락하는 속성을 가진 메시지만 수신합니다. 자세한 내용은 [Amazon SNS 메시지 필터링](sns-message-filtering.md) 단원을 참조하십시오.

**참고**  
메시지 속성을 필터링에 사용하는 경우 값은 유효한 JSON 문자열이어야 합니다. 이렇게 하면 메시지가 메시지 속성 필터링이 활성화된 구독으로 전달됩니다.

## 메시지 속성 항목 및 유효성 검사
<a name="SNSMessageAttributesNTV"></a>

각 메시지 속성은 다음 항목으로 구성됩니다.
+ **Name** – 메시지 속성 이름에는 A-Z, a-z, 0-9, 밑줄(\$1), 하이픈(-) 및 마침표(.)와 같은 문자가 포함될 수 있습니다. 이름은 마침표로 시작하거나 끝나서는 안 되며 연속 마침표가 있으면 안 됩니다. 이름은 대소문자를 구별하며 메시지에 대한 모든 속성 이름 중에서 고유해야 합니다. 이름은 최대 256자일 수 있습니다. 이름은 `AWS.` 또는 `Amazon.`(또는 모든 대소문자 변형)으로 시작할 수 없습니다. 이러한 접두사는 Amazon Web Services에서 사용하도록 예약되어 있기 때문입니다.
+ **Type** – 지원되는 메시지 속성 데이터 형식은 `String`, `String.Array`, `Number` 및 `Binary`입니다. 데이터 형식은 내용에 대해 메시지 본문과 동일한 제한 사항이 있습니다. 자세한 정보는 [메시지 속성 데이터 형식 및 유효성 검사](#SNSMessageAttributes.DataTypes) 섹션을 참조하세요.
+ **Value** – 사용자가 지정한 메시지 속성 값입니다. 문자열 데이터 유형의 경우 값 속성은 메시지 본문과 동일한 내용 제한을 따라야 합니다. 그러나 메시지 속성을 필터링에 사용하는 경우 Amazon SNS 구독 필터 정책과의 호환성을 보장하려면 값이 유효한 JSON 문자열이어야 합니다. 자세한 정보는 *Amazon Simple Notification Service API 참조*의 [게시](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) 작업을 참조하세요.

이름, 형식 및 값이 비어 있거나 널이면 안 됩니다. 또한 메시지 본문도 비어 있거나 널이면 안 됩니다. 이름, 형식 및 값을 포함하여 메시지 속성의 모든 부분은 256KB인 메시지 크기 제한에 포함됩니다.

## 메시지 속성 데이터 형식 및 유효성 검사
<a name="SNSMessageAttributes.DataTypes"></a>

메시지 속성 데이터 형식은 메시지 속성 값이 Amazon SNS에서 처리되는 방식을 식별합니다. 예를 들어, 형식이 숫자이면 Amazon SNS는 값이 숫자인지 확인합니다.

Amazon SNS는 명시된 경우를 제외하고 모든 엔드포인트에 대해 다음 논리적 데이터 유형을 지원합니다.
+ **String** – 문자열은 UTF-8 이진 인코딩을 사용하는 유니코드입니다. 코드 값 목록은 [http://en.wikipedia.org/wiki/ASCII\$1ASCII\$1printable\$1characters](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters)를 참조하세요.
**참고**  
대리 값은 메시지 속성에서 지원되지 않습니다. 예를 들어, 이모티콘을 나타내는 대리 값을 사용하면 “`Invalid attribute value was passed in for message attribute`“와 같은 오류가 발생합니다.
+ **String.Array** – 여러 값이 포함될 수 있는 문자열 형식의 배열입니다. 값은 문자열, 숫자 또는 키워드 `true`, `false` 및 `null`일 수 있습니다. 숫자 또는 부울 형식의 String.Array에는 따옴표가 필요하지 않습니다. String.Array 값이 여러 개인 경우 쉼표로 구분합니다.

  구독에는이 데이터 유형이 지원되지 않습니다 AWS Lambda . Lambda 엔드포인트에 대해 이 데이터 유형을 지정하면 Amazon SNS가 Lambda에 전달하는 JSON 페이로드의 `String` 데이터 유형으로 전달됩니다.
+ **Number** – 숫자는 양수 또는 음수 정수이거나 부동 소수점 숫자입니다. 숫자는 정수, 부동 소수점 수 및 실수가 일반적으로 지원하는 가능한 대부분의 값을 포함할 수 있는 충분한 범위와 정밀도를 갖추고 있습니다. 숫자 값은 -109에서 109까지 가능하며, 정확도는 소수점 이하 5자리입니다. 앞과 끝의 0은 잘립니다.

  구독에는이 데이터 유형이 지원되지 않습니다 AWS Lambda . Lambda 엔드포인트에 대해 이 데이터 유형을 지정하면 Amazon SNS가 Lambda에 전달하는 JSON 페이로드의 `String` 데이터 유형으로 전달됩니다.
+ **Binary** – 이전 형식 속성은 모든 이진 데이터를 저장할 수 있습니다(예: 압축된 데이터, 암호화된 데이터 또는 이미지).

## 모바일 푸시 알림에 예약된 메시지 속성
<a name="sns-attrib-mobile-reserved"></a>

다음 표에서는 푸시 알림 메시지를 구성하는 데 사용할 수 있는 모바일 푸시 알림 서비스에 예약된 메시지 속성을 나열합니다.

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/sns/latest/dg/sns-message-attributes.html)

1 메시지 속성이 요구 사항을 충족하지 않는 경우 Apple은 Amazon SNS 알림을 거부합니다. 자세한 내용은 Apple 개발자 웹 사이트에서 [APN에 알림 요청 보내기](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns)를 참조하세요.

# Amazon SNS 메시지 배치 처리
<a name="sns-batch-api-actions"></a>

## 메시지 일괄 처리란 무엇입니까?
<a name="what-is-message-batching"></a>

개별 `Publish` API 요청에서 표준 또는 FIFO 주제에 메시지를 게시하는 대신 Amazon SNS `PublishBatch` API를 사용하여 단일 API 요청에서 최대 10개의 메시지를 게시할 수 있습니다. 메시지를 배치로 전송하면 Amazon SNS를 통해 분산 애플리케이션 연결([A2A 메시징](sns-system-to-system-messaging.md)) 또는 사람에게 알림 전송([A2P 메시징](sns-user-notifications.md))과 관련된 비용을 최대 10배까지 줄일 수 있습니다. Amazon SNS에는 사용자가 운영 중인 리전에 따라 주제에 초당 게시할 수 있는 메시지 수에 대한 할당량이 있습니다. API 할당량에 대한 자세한 내용은 **AWS 일반 참조 가이드의 [Amazon SNS 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/sns.html) 페이지를 참조하세요.

**참고**  
단일 `PublishBatch` API 요청에서 전송하는 전체 메시지의 총 크기 합계는 262,144바이트(256KiB)를 초과할 수 없습니다.  
이 `PublishBatch` API는 IAM 정책에 대해 동일한 `Publish` API 작업을 사용합니다.

## 메시지 배치 처리는 어떻게 작동합니까?
<a name="message-batching-how-it-works"></a>

`PublishBatch` API를 사용하여 메시지를 게시하는 것은 `Publish` API를 사용하여 메시지를 게시하는 것과 유사합니다. 주된 차이점은 `PublishBatch` API 요청 내의 각 메시지에 고유한 배치 ID(최대 80자)가 할당되어야 한다는 것입니다. 이러한 방식으로 Amazon SNS는 배치 내의 모든 메시지에 대해 개별 API 응답을 반환하여 각 메시지가 게시되었는지 또는 오류가 발생했는지 확인할 수 있습니다. FIFO 주제에 게시되는 메시지의 경우 고유한 배치 ID 할당을 포함하는 것 외에도 각 개별 메시지에 대해 `MessageDeduplicationID` 및 `MessageGroupId`를 포함해야 합니다.

## 예시
<a name="message-batching-examples"></a>

**표준 주제에 10개의 메시지 배치 게시**

```
// Imports
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishBatchRequest;
import software.amazon.awssdk.services.sns.model.PublishBatchRequestEntry;
import software.amazon.awssdk.services.sns.model.PublishBatchResponse;
import software.amazon.awssdk.services.sns.model.SnsException;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// Code
private static final int MAX_BATCH_SIZE = 10;

public static void publishBatchToTopic(SnsClient snsClient, String topicArn, int batchSize) {
    try {
        // Validate the batch size
        if (batchSize > MAX_BATCH_SIZE) {
            throw new IllegalArgumentException("Batch size cannot exceed " + MAX_BATCH_SIZE);
        }

        // Create the batch entries
        List<PublishBatchRequestEntry> entries = IntStream.range(0, batchSize)
                .mapToObj(i -> PublishBatchRequestEntry.builder()
                        .id("id" + i)
                        .message("message" + i)
                        .build())
                .collect(Collectors.toList());

        // Build the batch request
        PublishBatchRequest request = PublishBatchRequest.builder()
                .topicArn(topicArn)
                .publishBatchRequestEntries(entries)
                .build();

        // Publish the batch request
        PublishBatchResponse response = snsClient.publishBatch(request);

        // Handle successful messages
        response.successful().forEach(success -> {
            System.out.println("Successful Batch Id: " + success.id());
            System.out.println("Message Id: " + success.messageId());
        });

        // Handle failed messages
        response.failed().forEach(failure -> {
            System.err.println("Failed Batch Id: " + failure.id());
            System.err.println("Error Code: " + failure.code());
            System.err.println("Sender Fault: " + failure.senderFault());
            System.err.println("Error Message: " + failure.message());
        });

    } catch (SnsException e) {
        // Log and handle exceptions
        System.err.println("SNS Exception: " + e.awsErrorDetails().errorMessage());
    } catch (IllegalArgumentException e) {
        System.err.println("Validation Error: " + e.getMessage());
    }
}
```

**FIFO 주제에 10개의 메시지 배치 게시**

```
// Imports
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishBatchRequest;
import software.amazon.awssdk.services.sns.model.PublishBatchRequestEntry;
import software.amazon.awssdk.services.sns.model.PublishBatchResponse;
import software.amazon.awssdk.services.sns.model.BatchResultErrorEntry;
import software.amazon.awssdk.services.sns.model.SnsException;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// Code
private static final int MAX_BATCH_SIZE = 10;

public static void publishBatchToFifoTopic(SnsClient snsClient, String topicArn) {
    try {
        // Create the batch entries to send
        List<PublishBatchRequestEntry> entries = IntStream.range(0, MAX_BATCH_SIZE)
                .mapToObj(i -> PublishBatchRequestEntry.builder()
                        .id("id" + i)
                        .message("message" + i)
                        .messageGroupId("groupId")
                        .messageDeduplicationId("deduplicationId" + i)
                        .build())
                .collect(Collectors.toList());

        // Create the batch request
        PublishBatchRequest request = PublishBatchRequest.builder()
                .topicArn(topicArn)
                .publishBatchRequestEntries(entries)
                .build();

        // Publish the batch request
        PublishBatchResponse response = snsClient.publishBatch(request);

        // Handle the successfully sent messages
        response.successful().forEach(success -> {
            System.out.println("Batch Id for successful message: " + success.id());
            System.out.println("Message Id for successful message: " + success.messageId());
            System.out.println("Sequence Number for successful message: " + success.sequenceNumber());
        });

        // Handle the failed messages
        response.failed().forEach(failure -> {
            System.err.println("Batch Id for failed message: " + failure.id());
            System.err.println("Error Code for failed message: " + failure.code());
            System.err.println("Sender Fault for failed message: " + failure.senderFault());
            System.err.println("Failure Message for failed message: " + failure.message());
        });

    } catch (SnsException e) {
        // Handle any exceptions from the request
        System.err.println("SNS Exception: " + e.awsErrorDetails().errorMessage());
    }
}
```

# Amazon SNS 주제 및 구독 삭제
<a name="sns-delete-subscription-topic"></a>

주제가 삭제되면 연결된 구독이 비동기식으로 삭제됩니다. 고객은 여전히 이러한 구독에 액세스할 수 있지만 동일한 이름을 사용하여 주제를 다시 만들더라도 구독은 더 이상 주제와 연결되지 않습니다. 게시자가 삭제된 주제에 메시지를 게시하려고 하면 게시자는 해당 주제가 존재하지 않는다는 오류 메시지를 받게 됩니다. 마찬가지로 삭제된 주제를 구독하려고 하면 오류 메시지가 표시됩니다. 확인이 보류 중인 구독은 삭제할 수 없습니다. Amazon SNS는 30일 후에 삭제되는 이메일 구독을 제외하고 48시간 후에 확인되지 않은 구독을 자동으로 삭제합니다.

**중요**  
 삭제된 Amazon SNS 주제는 복구할 수 없습니다. 주제를 삭제하기 전에 구독을 삭제하는 것이 좋습니다.  
 구독이 삭제되면 복구할 수 없습니다. Amazon SNS 주제에 게시된 알림은 삭제된 구독으로 전달되지 않습니다. 알림을 받으려면 구독을 다시 생성해야 합니다.

## 를 사용하여 Amazon SNS 주제 또는 구독을 삭제하려면 AWS Management Console
<a name="sns-delete-subscription-topic-console"></a>

Amazon SNS 주제 또는 구독을 삭제하면 효율적인 리소스 관리를 통해 불필요한 사용을 방지하고 Amazon SNS 콘솔을 정리할 수 있습니다. 이 단계는 유휴 리소스로 인한 잠재적 비용을 방지하고 더 이상 필요하지 않은 주제 또는 구독을 제거하여 관리를 간소화하는 데 도움이 됩니다.

**를 사용하여 주제를 삭제하려면 AWS Management Console**

1. [Amazon SNS 콘솔](https://console.aws.amazon.com/sns/home)에 로그인합니다.

1. 왼쪽의 탐색 창에서 **주제**를 선택합니다.

1. **주제** 페이지에서 주제를 선택한 다음, **삭제**를 선택합니다.

1. **삭제** 대화 상자에 `delete me`를 입력한 후 **삭제**를 선택합니다.

   콘솔에서 주제가 삭제됩니다.

**를 사용하여 구독을 삭제하려면 AWS Management Console**

1. [Amazon SNS 콘솔](https://console.aws.amazon.com/sns/home)에 로그인합니다.

1. 왼쪽의 탐색 창에서 **구독**을 선택합니다.

1. **구독** 페이지에서 상태가 **확인됨**인 구독을 선택한 다음 **삭제**를 선택합니다.

1. **구독 삭제** 대화 상자에서 **삭제**를 선택합니다.

   콘솔에서 구독이 삭제됩니다.

## AWS SDK를 사용하여 구독 및 주제를 삭제하려면
<a name="delete-topic-aws-sdks"></a>

 AWS SDK를 사용하려면 자격 증명으로 구성해야 합니다. [자세한 정보는 *AWS SDK 및 도구 참조 가이드*의 공유 구성 및 자격 증명 파일](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)을 참조하세요.

다음 코드 예시는 `DeleteTopic`의 사용 방법을 보여 줍니다.

------
#### [ .NET ]

**SDK for .NET**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/cross-service/TopicsAndQueues#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
주제 ARN으로 주제를 삭제합니다.  

```
    /// <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;
    }
```
+  API 세부 정보는 *AWS SDK for .NET API 참조*의 [DeleteTopic](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/DeleteTopic)을 참조하세요.

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
//! Delete an Amazon Simple Notification Service (Amazon SNS) topic.
/*!
  \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic.
  \param clientConfiguration: AWS client configuration.
  \return bool: Function succeeded.
 */
bool AwsDoc::SNS::deleteTopic(const Aws::String &topicARN,
                              const Aws::Client::ClientConfiguration &clientConfiguration) {
    Aws::SNS::SNSClient snsClient(clientConfiguration);

    Aws::SNS::Model::DeleteTopicRequest request;
    request.SetTopicArn(topicARN);

    const Aws::SNS::Model::DeleteTopicOutcome outcome = snsClient.DeleteTopic(request);

    if (outcome.IsSuccess()) {
        std::cout << "Successfully deleted the Amazon SNS topic " << topicARN << std::endl;
    }
    else {
        std::cerr << "Error deleting topic " << topicARN << ":" <<
                  outcome.GetError().GetMessage() << std::endl;
    }

    return outcome.IsSuccess();
}
```
+  API 세부 정보는 *AWS SDK for C\$1\$1 API 참조*의 [DeleteTopic](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/DeleteTopic)을 참조하세요.

------
#### [ CLI ]

**AWS CLI**  
**SNS 주제를 삭제하려면**  
다음 `delete-topic`예제에서는 지정된 SNS 주제를 삭제합니다.  

```
aws sns delete-topic \
    --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic"
```
이 명령은 출력을 생성하지 않습니다.  
+  API 세부 정보는 *AWS CLI 명령 참조*의 [DeleteTopic](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/delete-topic.html)을 참조하세요.

------
#### [ Go ]

**SDK for Go V2**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
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
}



// 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
}
```
+  API 세부 정보는 *AWS SDK for Go API 참조*의 [DeleteTopic](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.DeleteTopic)을 참조하세요.

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.DeleteTopicRequest;
import software.amazon.awssdk.services.sns.model.DeleteTopicResponse;
import software.amazon.awssdk.services.sns.model.SnsException;

/**
 * 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 DeleteTopic {
    public static void main(String[] args) {
        final String usage = """

                Usage:     <topicArn>

                Where:
                   topicArn - The ARN of the topic to delete.
                """;

        if (args.length != 1) {
            System.out.println(usage);
            System.exit(1);
        }

        String topicArn = args[0];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();

        System.out.println("Deleting a topic with name: " + topicArn);
        deleteSNSTopic(snsClient, topicArn);
        snsClient.close();
    }

    public static void deleteSNSTopic(SnsClient snsClient, String topicArn) {
        try {
            DeleteTopicRequest request = DeleteTopicRequest.builder()
                    .topicArn(topicArn)
                    .build();

            DeleteTopicResponse result = snsClient.deleteTopic(request);
            System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode());

        } catch (SnsException e) {
            System.err.println(e.awsErrorDetails().errorMessage());
            System.exit(1);
        }
    }
}
```
+  API 세부 정보는 *AWS SDK for Java 2.x API 참조*의 [DeleteTopic](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/DeleteTopic)을 참조하세요.

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
별도의 모듈에서 클라이언트를 생성하고 내보냅니다.  

```
import { SNSClient } from "@aws-sdk/client-sns";

// The AWS Region can be provided here using the `region` property. If you leave it blank
// the SDK will default to the region set in your AWS config.
export const snsClient = new SNSClient({});
```
SDK 및 클라이언트 모듈을 가져오고 API를 호출합니다.  

```
import { DeleteTopicCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string} topicArn - The ARN of the topic to delete.
 */
export const deleteTopic = async (topicArn = "TOPIC_ARN") => {
  const response = await snsClient.send(
    new DeleteTopicCommand({ TopicArn: topicArn }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'a10e2886-5a8f-5114-af36-75bd39498332',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
};
```
+  자세한 정보는 [AWS SDK for JavaScript 개발자 안내서](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-managing-topics.html#sns-examples-managing-topics-deletetopic)를 참조하세요.
+  API 세부 정보는 *AWS SDK for JavaScript API 참조*의 [DeleteTopic](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/DeleteTopicCommand)을 참조하세요.

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
suspend fun deleteSNSTopic(topicArnVal: String) {
    val request =
        DeleteTopicRequest {
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        snsClient.deleteTopic(request)
        println("$topicArnVal was successfully deleted.")
    }
}
```
+  API 세부 정보는 *AWS SDK for Kotlin API 참조*의 [DeleteTopic](https://sdk.amazonaws.com/kotlin/api/latest/index.html)를 참조하세요.

------
#### [ PHP ]

**SDK for PHP**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * Deletes an SNS topic and all its subscriptions.
 *
 * This code expects that you have AWS credentials set up per:
 * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html
 */

$SnSclient = new SnsClient([
    'profile' => 'default',
    'region' => 'us-east-1',
    'version' => '2010-03-31'
]);

$topic = 'arn:aws:sns:us-east-1:111122223333:MyTopic';

try {
    $result = $SnSclient->deleteTopic([
        'TopicArn' => $topic,
    ]);
    var_dump($result);
} catch (AwsException $e) {
    // output error message if fails
    error_log($e->getMessage());
}
```
+  API 세부 정보는 *AWS SDK for PHP API 참조*의 [DeleteTopic](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/DeleteTopic)을 참조하세요.

------
#### [ Python ]

**SDK for Python (Boto3)**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
class SnsWrapper:
    """Encapsulates Amazon SNS topic and subscription functions."""

    def __init__(self, sns_resource):
        """
        :param sns_resource: A Boto3 Amazon SNS resource.
        """
        self.sns_resource = sns_resource


    @staticmethod
    def delete_topic(topic):
        """
        Deletes a topic. All subscriptions to the topic are also deleted.
        """
        try:
            topic.delete()
            logger.info("Deleted topic %s.", topic.arn)
        except ClientError:
            logger.exception("Couldn't delete topic %s.", topic.arn)
            raise
```

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def delete_topic(self, topic_arn: str) -> bool:
        """
        Delete an SNS topic.

        :param topic_arn: The ARN of the topic to delete.
        :return: True if successful.
        :raises ClientError: If the topic deletion fails.
        """
        try:
            self.sns_client.delete_topic(TopicArn=topic_arn)
            
            logger.info(f"Deleted topic: {topic_arn}")
            return True

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            
            if error_code == 'NotFound':
                logger.warning(f"Topic not found: {topic_arn}")
                return True  # Already deleted
            else:
                logger.error(f"Error deleting topic: {error_code} - {e}")
                raise
```
+  API 세부 정보는 *AWS SDK for Python (Boto3) API 참조*의 [DeleteTopic](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/DeleteTopic)를 참조하세요.

------
#### [ SAP ABAP ]

**SDK for SAP ABAP API**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
    TRY.
        lo_sns->deletetopic( iv_topicarn = iv_topic_arn ).
        MESSAGE 'SNS topic deleted.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
+  API에 대한 세부 정보는 *SAP ABAP용AWS SDK API 참조*의 [DeleteTopic](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)을 참조하세요.

------
#### [ Swift ]

**SDK for Swift**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        _ = try await snsClient.deleteTopic(
            input: DeleteTopicInput(topicArn: arn)
        )
```
+  API 세부 정보는 *AWS SDK for Swift API 참조*의 [DeleteTopic](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/deletetopic(input:)) 섹션을 참조하세요.

------

# 다음 단계
<a name="sns-next-steps-getting-started"></a>

구독이 있는 주제를 만들고 주제에 메시지를 보냈으므로 이제 다음 작업을 시도해 볼 수 있습니다.
+ [AWS 개발자 센터](https://aws.amazon.com/developer/)를 살펴봅니다.
+ [보안](security.md) 섹션에서 데이터를 보호하는 방법에 대해 알아봅니다.
+ 주제에 대해 [서버 측 암호화](sns-enable-encryption-for-topic.md)를 사용합니다.
+ [암호화된 Amazon Simple Queue Service(Amazon SQS) 대기열](sns-enable-encryption-for-topic-sqs-queue-subscriptions.md)에서 구독하는 주제에 대해 서버 측 암호화를 사용합니다.
+ [AWS Event Fork Pipelines](sns-subscribe-event-fork-pipelines.md)에서 주제를 구독합니다.