아마존 SNS 주제 만들기 - Amazon Simple Notification Service

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

아마존 SNS 주제 만들기

Amazon SNS 토픽은 커뮤니케이션 채널 역할을 하는 논리적 액세스 포인트입니다. 주제를 사용하면 여러 엔드포인트 (예: Amazon AWS Lambda SQS, 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 계정 이전에 만든 주제가 없는 경우 SNS 홈페이지에서 Amazon에 대한 설명을 읽어보십시오.

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

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

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

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

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

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

      중요

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

    4. (선택 사항) 특정 FIFO 주제의 경우 콘텐츠 기반 메시지 중복 제거를 선택하여 기본 메시지 중복 제거를 활성화할 수 있습니다. 자세한 내용은 주제에 대한 Amazon SNS 메시지 중복 제거 FIFO 단원을 참조하십시오.

  5. (선택 사항) 암호화 섹션을 확장하고 다음을 수행합니다. 자세한 내용은 서버 측 암호화를 통한 Amazon SNS 데이터 보호 단원을 참조하십시오.

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

    2. 키를 지정합니다. AWS KMS 자세한 내용은 주요 용어 단원을 참조하십시오.

      각 KMS 유형마다 설명, 계정 KMSARN등이 표시됩니다.

      중요

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

      소유자에게 이러한 권한을 KMS 부여해 달라고 요청하십시오. 자세한 내용은 AWS Key Management Service 개발자 안내서의AWS KMS API 권한: 작업 및 리소스 참조를 참조하십시오.

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

        참고

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

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

        • 또는 SSE 활성화된 상태에서 주제에 대한 Publish 작업을 처음 사용하면 KMS Amazon용 AWS 관리형 작업이 AWS KMS 생성됩니다SNS.

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

        참고

        사용자 지정 KMSs 생성에 대한 지침은 AWS Key Management Service 개발자 안내서의 키 생성을 참조하십시오.

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

  6. (선택 사항) 기본적으로 주제 소유자만 주제에 게시하거나 주제를 구독할 수 있습니다. 추가 액세스 권한을 구성하려면 액세스 정책 섹션을 확장합니다. 자세한 내용은 Amazon의 자격 증명 및 액세스 관리 SNSAmazon SNS 액세스 제어의 예시 사례 단원을 참조하세요.

    참고

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

  7. (선택 사항) Amazon에서 실패한 메시지 전송 시도를 SNS 재시도하는 방법을 구성하려면 전송 재시도 정책 (HTTP/S) 섹션을 확장하십시오. 자세한 내용은 Amazon SNS 메시지 전송 재시도 단원을 참조하십시오.

  8. (선택 사항) Amazon에서 메시지 전송을 SNS 로깅하는 방법을 구성하려면 CloudWatch 전송 상태 로깅 섹션을 확장하십시오. 자세한 내용은 Amazon SNS 메시지 전송 상태 단원을 참조하십시오.

  9. (선택 사항) 메타데이터 태그를 주제에 추가하려면 태그 섹션을 확장하고, (옵션)을 입력한 다음 태그 추가를 선택합니다. 자세한 내용은 아마존 SNS 주제 태깅 단원을 참조하십시오.

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

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

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

  11. 주제를 ARN 클립보드에 복사합니다. 예를 들면 다음과 같습니다.

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

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

를 AWS SDK 사용하려면 자격 증명으로 구성해야 합니다. 자세한 내용은 및 도구 참조 안내서의 공유 구성 및 자격 증명 파일을 참조하십시오.AWS SDKs

다음 코드 예제는 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 내용은 CreateTopic참조를 참조하십시오.AWS SDK for .NET API

C++
SDKC++의 경우
참고

더 많은 정보가 있습니다. 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(); }
CLI
AWS CLI

SNS주제를 만들려면

다음 create-topic 예제에서는 라는 SNS 주제를 생성합니다my-topic.

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

  • 자세한 API 내용은 AWS CLI 명령 CreateTopic참조를 참조하십시오.

Go
SDKGo 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 }
Java
SDK자바 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 ""; } }
JavaScript
SDK JavaScript (v3) 에 대한
참고

더 많은 정보가 있습니다. 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코틀린의 경우
참고

더 많은 정보가 있습니다. 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 AWS SDK내용은 Kotlin API 참조를 참조하세요 CreateTopic.

PHP
PHP용 SDK
참고

자세한 내용은 다음과 같습니다. 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파이썬용 (보토3)
참고

더 많은 정보가 있습니다. 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내용은 Python (Boto3) API 참조를 참조하십시오 CreateTopic.

Ruby
SDK루비의 경우
참고

더 많은 정보가 있습니다. 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
SDKRust의 경우
참고

더 많은 정보가 있습니다 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 AWS SDK내용은 Rust API 참조를 참조하십시오 CreateTopic.

SAP ABAP
SDK... 에 대한 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 AWS SDK내용은 CreateTopic에서 SAP ABAP API 참조를 참조하십시오.