AWSDocAWS SDKGitHub サンプルリポジトリには、さらに多くの SDK サンプルがあります
翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
AWS SDK を使用して Amazon SNS トピックへ発行する
次のコード例は、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. The code uses the AWS SDK for .NET and /// .NET Core 5.0. /// </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}"); } }
-
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 forJavaScript v3)
-
注記
他にもありますGitHub。用例一覧を検索し、AWS コード例リポジトリ
での設定と実行の方法を確認してください。 別のモジュールでクライアントを作成し、エクスポートします。
import { SNSClient } from "@aws-sdk/client-sns"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create SNS service object. const snsClient = new SNSClient({ region: REGION }); export { snsClient };
SDK モジュールとクライアントモジュールをインポートし、API を呼び出します。
// Import required AWS SDK clients and commands for Node.js import {PublishCommand } from "@aws-sdk/client-sns"; import {snsClient } from "./libs/snsClient.js"; // Set the parameters var params = { Message: "MESSAGE_TEXT", // MESSAGE_TEXT TopicArn: "TOPIC_ARN", //TOPIC_ARN }; const run = async () => { try { const data = await snsClient.send(new PublishCommand(params)); console.log("Success.", data); return data; // For unit tests. } catch (err) { console.log("Error", err.stack); } }; run();
-
詳細については、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 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 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
-
注記
これはデベロッパープレビューリリースの SDK に関するドキュメントです。SDK は変更される場合があるため、本稼働環境での使用はお勧めできません。
注記
他にもあります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」(発行) を参照してください。
-