Amazon SNS メッセージの発行
Amazon SNS トピックを作成して、このトピックにエンドポイントをサブスクライブしたら、トピックにメッセージを発行できます。メッセージが公開されると、Amazon SNS はサブスクライブされたエンドポイントにメッセージを配信しようとします。
トピック
AWS Management Console を使用してAmazon SNS トピックにメッセージを発行するには
Amazon SNS コンソール
にサインインします。 -
左のナビゲーションペインで、[トピック] を選択します。
-
[トピック] ページで、トピックを選択し、[メッセージの発行] を選択します。
コンソールが [トピックにメッセージを発行] ページを開きます。
-
[メッセージ詳細] セクションで、次の操作を行います。
-
(オプション) メッセージの件名を入力します。
-
FIFO トピックは、メッセージグループ ID を入力します。同じメッセージグループ内のメッセージは、発行された順序で配信されます。
-
FIFO トピックは、メッセージ重複排除 ID を入力します。トピックの[コンテンツベースのメッセージ重複除外] 設定を有効にしていれば、この ID は任意です。
-
(オプション) モバイルプッシュ通知に、有効期限 (TTL) 値を秒単位で入力します。この属性で、Apple Push Notification Service (APNs) や Firebase Cloud Messaging (FCM) などのプッシュ通知サービスによってエンドポイントにメッセージが配信される時間を指定できます。
-
-
[メッセージ本文] セクションで、以下のいずれかの操作を行います。
-
[すべての配信プロトコルに同一のペイロード] を選択し、メッセージを入力します。
-
[各配信プロトコルのカスタムペイロード] を選択し、JSON オブジェクトを入力し、各プロトコルに送信するメッセージを定義します。
詳細については、「プラットフォーム固有のペイロードで発行する」を参照してください。
-
-
[メッセージの属性] セクションで、属性を追加します。Amazon SNS は、追加された属性とサブスクリプション属性
FilterPolicy
をマッチングし、サブスクライブされたエンドポイントが、発行されたメッセージに関心があるかどうかを判断します。-
タイプでは、String.Array などの属性タイプを選択します。
注記
属性のタイプが String.Array である場合は、配列を角括弧 (
[]
) で囲みます。配列内で、値の文字列を二重引用符で囲みます。数字またはキーワードtrue
、false
、null
を引用符で囲む必要はありません。 -
customer_interests
などの属性の名前を入力します。 -
["soccer", "rugby", "hockey"]
などの属性の値を入力します。
属性のタイプが、String、String.Array、または Number である場合、フィルターポリシー (存在する場合) の範囲が明示的に
MessageBody
に設定されていなければ、Amazon SNS はサブスクリプションにメッセージを送信する前に、サブスクリプションのフィルターポリシーに照らしてメッセージ属性を評価します。詳細については、「Amazon SNS メッセージ属性」を参照してください。
-
-
[メッセージの発行] を選択します。
トピックにメッセージが発行され、コンソールがトピックの [詳細] ページを開きます。
AWS SDK を使用してトピックにメッセージを発行するには
AWS SDK を使用するには、認証情報を使用して設定する必要があります。詳細については、『AWS SDK とツールのリファレンスガイド』の「共有設定ファイルと認証情報ファイル」を参照してください。
次のコード例は、Amazon SNS トピックにメッセージを発行する方法を示しています。
- .NET
-
- AWS SDK for .NET
-
注記
GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 トピックへのメッセージの発行
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}"); } }
属性と、オプションの重複およびグループ ID を指定してメッセージをトピックに発行します。
/// <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 .NETAPI リファレンスの「発行」を参照してください。
-
- C++
-
- SDK for C++
-
注記
GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 //! 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(); }
-
API の詳細については、AWS SDK for C++API リファレンスの「発行」を参照してください。
-
- Go
-
- SDK for Go V2
-
注記
GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 package main import ( "context" "flag" "fmt" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/sns" ) // SNSPublishAPI defines the interface for the Publish function. // We use this interface to test the function using a mocked service. type SNSPublishAPI interface { Publish(ctx context.Context, params *sns.PublishInput, optFns ...func(*sns.Options)) (*sns.PublishOutput, error) } // PublishMessage publishes a message to an Amazon Simple Notification Service (Amazon SNS) topic // Inputs: // c is the context of the method call, which includes the Region // api is the interface that defines the method call // input defines the input arguments to the service call. // Output: // If success, a PublishOutput object containing the result of the service call and nil // Otherwise, nil and an error from the call to Publish func PublishMessage(c context.Context, api SNSPublishAPI, input *sns.PublishInput) (*sns.PublishOutput, error) { return api.Publish(c, input) } func main() { msg := flag.String("m", "", "The message to send to the subscribed users of the topic") topicARN := flag.String("t", "", "The ARN of the topic to which the user subscribes") flag.Parse() if *msg == "" || *topicARN == "" { fmt.Println("You must supply a message and topic ARN") fmt.Println("-m MESSAGE -t TOPIC-ARN") return } cfg, err := config.LoadDefaultConfig(context.TODO()) if err != nil { panic("configuration error, " + err.Error()) } client := sns.NewFromConfig(cfg) input := &sns.PublishInput{ Message: msg, TopicArn: topicARN, } result, err := PublishMessage(context.TODO(), client, input) if err != nil { fmt.Println("Got an error publishing the message:") fmt.Println(err) return } fmt.Println("Message ID: " + *result.MessageId) }
-
API の詳細については、AWS SDK for GoAPI リファレンスの「発行
」を参照してください。
-
- Java
-
- SDK for Java 2.x
-
注記
GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 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.xAPI リファレンスの「発行」を参照してください。
-
- JavaScript
-
- SDK for 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 { 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; };
-
詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。
-
API の詳細については、AWS SDK for JavaScriptAPI リファレンスの「発行」を参照してください。
-
- Kotlin
-
- SDK for Kotlin
-
注記
これはプレビューリリースの機能に関するプレリリースドキュメントです。このドキュメントは変更される可能性があります。
注記
GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 suspend fun pubTopic(topicArnVal: String, messageVal: String) { val request = PublishRequest { message = messageVal topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.publish(request) println("${result.messageId} message sent.") } }
-
API の詳細については、AWS SDK for Kotlin API リファレンスの「Publish
」を参照してください。
-
- PHP
-
- SDK for PHP
-
注記
GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 require 'vendor/autoload.php'; use Aws\Sns\SnsClient; use Aws\Exception\AwsException; /** * 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 デベロッパーガイド」を参照してください。
-
API の詳細については、AWS SDK for PHPAPI リファレンスの「発行」を参照してください。
-
- 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 @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, text-only version of the message while an email subscriber could receive an HTML version of the message. :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
-
API の詳細については、AWSSDK for Python (Boto3) API リファレンスの「発行」を参照してください。
-
- Ruby
-
- SDK for Ruby
-
注記
GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 require "aws-sdk-sns" # v2: require 'aws-sdk' def message_sent?(sns_client, topic_arn, message) sns_client.publish(topic_arn: topic_arn, message: message) rescue StandardError => e puts "Error while sending the message: #{e.message}" end def run_me topic_arn = "SNS_TOPIC_ARN" region = "REGION" message = "MESSAGE" # The text of the message to send. sns_client = Aws::SNS::Client.new(region: region) puts "Message sending." if message_sent?(sns_client, topic_arn, message) puts "The message was sent." else puts "The message was not sent. Stopping program." exit 1 end end run_me if $PROGRAM_NAME == __FILE__
-
詳細については、「AWS SDK for Ruby デベロッパーガイド」を参照してください。
-
API の詳細については、AWS SDK for RubyAPI リファレンスの「発行」を参照してください。
-
- Rust
-
- SDK for Rust
-
注記
これはプレビューリリースの SDK に関するドキュメントです。SDK は変更される場合があり、本稼働環境では使用しないでください。
注記
GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 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 リファレンスの「発行
」を参照してください。
-
- SAP ABAP
-
- SDK for SAP ABAP
-
注記
GitHub には、その他のリソースもあります。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 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.
-
API の詳細については、AWS SDK for SAP ABAP API リファレンスの「Publish」(発行) を参照してください。
-