翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
Amazon SNS トピックを作成する
Amazon SNS トピックは、通信チャネルとして機能する論理アクセスポイントです。トピックでは、複数のエンドポイント (Amazon SQS、HTTP/S AWS Lambda、E メールアドレスなど) をグループ化できます。
メッセージプロデューサーシステム (e コマースウェブサイトなど) で当システムのメッセージを必要とする他の複数のサービス (チェックアウトシステムやフルフィルメントシステムなど) にメッセージをブロードキャストするには、プロデューサーシステムのトピックを作成できます。
Amazon SNS で最も一般的な最初のタスクは、トピックの作成です。このページでは AWS Management Console、、、を使用してトピックを作成する方法を説明します。 AWS SDK for Java AWS SDK for .NET
作成時に、トピックタイプ (標準または FIFO) を選択し、トピックに名前を付けます。トピックを作成したら、トピックのタイプや名前を変更することはできません。その他の設定項目はすべて、トピックの作成時にオプションであり、後で編集できます。
個人を特定できる情報 (PII) などの機密情報や秘匿性の高い情報はトピック名に追加しないでください。トピック名には、 CloudWatch ログを含む他のAmazon Web Services からアクセスできます。トピック名は、プライベートデータや機密データとして使用することを意図していません。
を使用してトピックを作成するには AWS Management Console
Amazon SNS コンソールにサインインします。
-
次のいずれかを行います。
-
[トピック] ページで、[トピックの作成] を選択します。
-
[サブスクリプションの作成] ページで [詳細] セクションで、以下を実行します。
-
[タイプ] で、トピックタイプ (標準またはFIFO) を選択します。
-
トピックの名前を入力します。FIFO トピックで、名前の末尾に .fifo を追加します。
-
(オプション) トピックの表示名を入力します。
E メールエンドポイントをサブスクライブする場合、Amazon SNS トピックの表示名と送信 E メールアドレス (例えば、no-reply@sns.amazonaws.com) の合計文字数が 320 UTF-8 文字を超えてはなりません。Amazon SNS トピックの表示名を設定する前に、サードパーティーのエンコードツールを使用して送信アドレスの長さを確認できます。
-
(オプション) FIFO トピックで、[コンテンツベースのメッセージ重複排除] を選択して、デフォルトのメッセージの重複排除を有効にします。詳細については、「FIFO トピックのメッセージ重複除外」を参照してください。
-
(オプション) [暗号化] セクションを展開し、以下の操作を実行します。詳細については、「保管中の暗号化」を参照してください。
-
[暗号化の有効化] を選択します。
-
AWS KMS キーを指定します。詳細については、「重要な用語」を参照してください。
KMS タイプごとに、[Description] (説明)、[Account] (アカウント)、および [KMS ARN] が表示されます。
KMS の所有者ではない場合、または kms:ListAliases
および kms:DescribeKey
の許可がないアカウントでログインした場合、Amazon SNS コンソールで KMS に関する情報を表示できません。
これらの許可を付与するように、KMS の所有者へ依頼してください。詳細については、「AWS Key Management Service デベロッパーガイド」の「AWS KMS API アクセス権限: アクションとリソースのリファレンス」を参照してください。
-
Amazon SNS (デフォルト) エイリアス/AWS/SNS AWS 用のマネージド KMS がデフォルトで選択されています。
以下に留意してください。
-
初めてを使用してトピックの AWS Management Console Amazon SNS AWS 用のマネージド KMS AWS KMS を指定すると、Amazon SNS AWS 用のマネージド KMS が作成されます。
-
または、SSE Publish
が有効になっているトピックでアクションを初めて使用したときに、Amazon SNS AWS 用のマネージド KMS AWS KMS を作成します。
-
AWS アカウントからカスタム KMS を使用するには、KMS キーフィールドを選択し、リストからカスタム KMS を選択します。
カスタム KMS の作成手順については、AWS Key Management Service デベロッパーガイドの「キーの作成」を参照してください。
-
AWS AWS 自分のアカウントまたは別のアカウントのカスタム KMS ARN を使用するには、KMS キーフィールドに入力します。
-
(オプション) デフォルトでは、トピックの所有者のみがトピックを発行またはサブスクライブできます。追加のアクセス許可を設定するには、[アクセスポリシー] セクションを展開します。詳細については、「Amazon SNS での Identity and Access Management」および「Amazon SNS アクセスコントロールのケース例」を参照してください。
コンソールを使用してトピックを作成すると、デフォルトのポリシーでは aws:SourceOwner
条件キーが使用されます。このキーは aws:SourceAccount
に類似しています。
-
(オプション) 失敗したメッセージ配信試行を Amazon SNS で再試行する方法を設定するには、[配信再試行ポリシー (HTTP/S)] セクションを展開します。詳細については、「Amazon SNS メッセージ配信の再試行」を参照してください。
-
(オプション) Amazon SNS がメッセージの配信を記録する方法を設定するには CloudWatch、[配信ステータスロギング] セクションを展開します。詳細については、「Amazon SNS メッセージ配信ステータス」を参照してください。
-
(オプション) トピックにメタデータタグを追加するには、[タグ] セクションを展開し、[キー] と [値] (オプション) に入力し、[タグの追加] を選択します。詳細については、「Amazon SNS トピックのタグ付け」を参照してください。
-
[Create topic] (トピックの作成) を選択します。
トピックが作成され、MyTopic
ページが表示されます。
トピックの名前、ARN、(オプション) 表示名、 AWS トピック所有者のアカウント ID が [詳細] セクションに表示されます。
-
トピック ARN をクリップボードにコピーします。例:
arn:aws:sns:us-east-2:123456789012:MyTopic
SDK を使用してトピックを作成するには AWS
AWS SDK を使用するには、認証情報を使用して設定する必要があります。詳細については、「AWS SDK とツールのリファレンスガイド」の「共有設定ファイルと認証情報ファイル」を参照してください。
次のコード例は使用方法を示していますCreateTopic
。
- .NET
-
- AWS SDK for .NET
-
トピックを作成して、個別の名前を付けます。
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;
}
- C++
-
- SDK for C++
-
//! 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
-
- Go
-
- SDK for Go V2
-
// 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 for Java 2.x
-
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
-
- JavaScript (v3) 用の SDK
-
別のモジュールでクライアントを作成し、エクスポートします。
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
-
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()
}
}
- PHP
-
- SDK for PHP
-
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)
-
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
- Ruby
-
- SDK for Ruby
-
# 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
-
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(())
}
- SAP ABAP
-
- SDK for SAP ABAP
-
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.