Amazon SNS 주제 생성 - Amazon Simple Notification Service

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

Amazon SNS 주제 생성

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

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

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

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

중요

개인 식별 정보(PII)나 기타 기밀 정보 또는 민감한 정보를 주제 이름에 추가하지 마십시오. 주제 이름은 CloudWatch 로그를 비롯한 다른 Amazon Web Services에서 액세스할 수 있습니다. 주제 이름은 개인 데이터나 민감한 데이터에 사용하기 위한 것이 아닙니다.

를 사용하여 주제를 만들려면 AWS Management Console

  1. Amazon SNS 콘솔에 로그인합니다.

  2. 다음 중 하나를 수행하십시오.

    • AWS 계정 이전에 생성한 주제가 없는 경우 홈 페이지에서 Amazon SNS 설명을 읽어보십시오.

    • AWS 계정 이전에 주제를 생성한 적이 있는 경우 탐색 패널에서 주제를 선택합니다.

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

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

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

    2. 주제의 이름을 입력합니다. FIFO 주제의 경우 이름 끝에 .fifo를 추가합니다.

    3. (선택 사항) 주제의 표시 이름을 입력합니다.

      중요

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

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

  5. (선택 사항) 암호화 섹션을 확장하고 다음을 수행합니다. 자세한 정보는 저장 시 암호화을 참조하세요.

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

    2. AWS KMS 키를 지정합니다. 자세한 정보는 주요 용어을 참조하세요.

      각 KMS 유형에 대해 설명(Description), 계정(Account), KMS ARN이 표시됩니다.

      중요

      해당 KMS의 소유자가 아니거나 kms:ListAliaseskms:DescribeKey 권한이 없는 계정으로 로그인하는 경우 Amazon SNS 콘솔에서 해당 KMS에 대한 정보를 볼 수 없습니다.

      KMS의 소유자에게 이 권한을 부여해 달라고 요청해야 합니다. 자세한 정보는 AWS Key Management Service 개발자 안내서AWS KMS API 권한: 작업 및 리소스 참조를 참조하세요.

      • Amazon SNS용 AWS 관리형 KMS (기본값) 별칭/AWS/sns가 기본적으로 선택됩니다.

        참고

        다음 사항에 유의하십시오:

        • 를 사용하여 주제에 대해 Amazon SNS용 AWS 관리형 KMS를 처음으로 지정하면 Amazon SNS용 AWS 관리형 KMS가 AWS KMS 생성됩니다. AWS Management Console

        • 또는 SSE가 활성화된 주제에 대해 처음으로 Publish 작업을 사용할 때 Amazon SNS용 AWS 관리형 KMS가 AWS KMS 생성됩니다.

      • AWS 계정의 사용자 지정 KMS를 사용하려면 KMS 키 필드를 선택한 다음 목록에서 사용자 지정 KMS를 선택합니다.

        참고

        사용자 지정 KMS 생성에 대한 지침은 AWS Key Management Service 개발자 안내서키 생성을 참조하세요.

      • 사용자 계정 또는 AWS 다른 계정의 사용자 지정 KMS AWS ARN을 사용하려면 KMS 키 필드에 해당 ARN을 입력합니다.

  6. (선택 사항) 기본적으로 주제 소유자만 주제에 게시하거나 주제를 구독할 수 있습니다. 추가 액세스 권한을 구성하려면 액세스 정책 섹션을 확장합니다. 자세한 정보는 Amazon SNS의 Identity and Access ManagementAmazon SNS 액세스 제어의 예제 사례에서 확인하세요.

    참고

    콘솔을 사용하여 주제를 생성하는 경우 기본 정책은 aws:SourceOwner 조건 키를 사용합니다. 이 키는 aws:SourceAccount와 비슷합니다.

  7. (선택 사항) Amazon SNS가 실패한 메시지 전송을 재시도하는 방식을 구성하려면 전송 재시도 정책(HTTP/S) 섹션을 확장합니다. 자세한 정보는 Amazon SNS 메시지 전송 재시도을 참조하세요.

  8. (선택 사항) Amazon SNS가 메시지 전송을 로깅하는 방법을 구성하려면 CloudWatch 전송 상태 로깅 섹션을 확장하십시오. 자세한 정보는 Amazon SNS 메시지 전송 상태을 참조하세요.

  9. (선택 사항) 메타데이터 태그를 주제에 추가하려면 태그 섹션을 확장하고, (옵션)을 입력한 다음 태그 추가를 선택합니다. 자세한 정보는 Amazon SNS 주제 태그 지정을 참조하세요.

  10. 주제 생성을 선택합니다.

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

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

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

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

SDK를 AWS 사용하여 주제를 만들려면

AWS SDK를 사용하려면 사용자 인증 정보로 구성해야 합니다. 자세한 정보는 AWS SDK 및 도구 참조 가이드의 공유 구성 및 자격 증명 파일을 참조하세요.

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

.NET
AWS SDK for .NET
참고

더 많은 내용이 있습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

특정 이름으로 주제를 생성합니다.

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참조를 참조하십시오.

C++
SDK for C++
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

//! 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++ API 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에서 AWS 명령줄 인터페이스 사용을 참조하십시오.

  • API 세부 정보는 AWS CLI 명령 CreateTopic참조를 참조하십시오.

Go
SDK for Go V2
참고

자세한 내용은 에서 확인할 수 GitHub 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// 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(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(context.TODO(), &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참조를 참조하십시오.

Java
SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

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참조를 참조하십시오.

JavaScript
JavaScript (v3) 용 SDK
참고

더 많은 내용이 있습니다. GitHub AWS 코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

별도의 모듈에서 클라이언트를 생성하고 내보냅니다.

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; };
Kotlin
SDK for Kotlin
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

suspend fun createSNSTopic(topicName: String): String { val request = CreateTopicRequest { name = topicName } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.createTopic(request) return result.topicArn.toString() } }
  • API 세부 정보는 Kotlin API용AWS SDK 레퍼런스를 참조하세요 CreateTopic.

PHP
SDK for PHP
참고

자세한 내용은 여기에서 확인할 수 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

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()); }
Python
SDK for Python(Boto3)
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

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
  • API에 대한 자세한 내용은 파이썬용AWS SDK (Boto3) API 레퍼런스를 참조하십시오 CreateTopic.

Ruby
SDK for Ruby
참고

자세한 내용은 여기에서 확인할 수 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

# 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
Rust
SDK for Rust
참고

자세한 내용은 다음과 같습니다 GitHub. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

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에 대한 자세한 내용은 Rust용AWS SDK API 레퍼런스를 참조하십시오 CreateTopic.

SAP ABAP
SDK for SAP ABAP
참고

자세한 내용은 여기에서 확인할 수 있습니다. GitHub AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

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용AWS SDK ABAP API 참조를 참조하십시오 CreateTopic.