

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Amazon SNS メッセージの発行
<a name="sns-publishing"></a>

[Amazon SNS トピックを作成](sns-create-topic.md)して、このトピックに[エンドポイントをサブスクライブ](sns-create-subscribe-endpoint-to-topic.md)したら、トピックにメッセージを*発行*できます。メッセージが公開されると、Amazon SNS はサブスクライブされた[エンドポイント](sns-create-subscribe-endpoint-to-topic.md#sns-endpoints)にメッセージを配信しようとします。

## を使用して Amazon SNS トピックにメッセージを発行するには AWS マネジメントコンソール
<a name="sns-publishing-messages"></a>

1. [Amazon SNS コンソール](https://console.aws.amazon.com/sns/home)にサインインします。

1. 左のナビゲーションペインで、[**トピック**] を選択します。

1. [**トピック**] ページで、トピックを選択し、[**メッセージの発行**] を選択します。

   コンソールが [**トピックにメッセージを発行**] ページを開きます。

1. [**メッセージ詳細**] セクションで、次の操作を行います。

   1. (オプション) メッセージの**件名**を入力します。

   1. [FIFO トピック](sns-fifo-topics.md)は、**メッセージグループ ID** を入力します。FIFO トピックには**メッセージグループ ID** が必要です。同じメッセージグループ内のメッセージは、発行された順序で配信されます。

   1. (オプション) 標準トピックの場合は、**メッセージグループ ID** を入力します。この ID はすべての Amazon SQS 標準サブスクリプションに転送され、他のエンドポイントタイプで使用されたり、他のエンドポイントタイプに送信されたりすることはありません。

   1. FIFO トピックは、**メッセージ重複排除 ID** を入力します。トピックの[**コンテンツベースのメッセージ重複除外**] 設定を有効にしていれば、この ID は任意です。

   1. (オプション) [モバイルプッシュ通知](sns-ttl.md)に、**有効期限 (TTL)** 値を秒単位で入力します。この属性で、Apple Push Notification Service (APNs) や Firebase Cloud Messaging (FCM) などのプッシュ通知サービスによってエンドポイントにメッセージが配信される時間を指定できます。

1. [**メッセージ本文**] セクションで、以下のいずれかの操作を行います。

   1. [**すべての配信プロトコルに同一のペイロード**] を選択し、メッセージを入力します。

   1. [**各配信プロトコルのカスタムペイロード**] を選択し、JSON オブジェクトを入力し、各プロトコルに送信するメッセージを定義します。

      詳細については、「[プラットフォーム固有のペイロードを使用した Amazon SNS 通知の発行](sns-send-custom-platform-specific-payloads-mobile-devices.md)」を参照してください。

1. [**メッセージの属性**] セクションで、属性を追加します。Amazon SNS は、追加された属性とサブスクリプション属性 `FilterPolicy` をマッチングし、サブスクライブされたエンドポイントが、発行されたメッセージに関心があるかどうかを判断します。

   1. **タイプ**では、**String.Array** などの属性タイプを選択します。
**注記**  
属性のタイプが **String.Array** である場合は、配列を角括弧 (`[]`) で囲みます。配列内で、値の文字列を二重引用符で囲みます。数字またはキーワード `true`、`false`、`null` を引用符で囲む必要はありません。

   1. `customer_interests` などの属性の**名前**を入力します。

   1. `["soccer", "rugby", "hockey"]` などの属性の**値**を入力します。

   属性のタイプが、**String**、**String.Array**、または **Number** である場合、フィルターポリシー (存在する場合) の範囲が明示的に `MessageBody` に設定されていなければ、Amazon SNS はサブスクリプションにメッセージを送信する前に、サブスクリプションの[フィルターポリシー](sns-message-filtering.md)に照らしてメッセージ属性を評価します。

   詳細については、「[Amazon SNS メッセージ属性](sns-message-attributes.md)」を参照してください。

1. [**メッセージの発行**] を選択します。

   トピックにメッセージが発行され、コンソールがトピックの [**詳細**] ページを開きます。

## AWS SDK を使用してトピックにメッセージを発行するには
<a name="publish-to-topic-aws-sdks"></a>

 AWS SDK を使用するには、認証情報を使用して設定する必要があります。詳細については、「*AWS SDK とツールのリファレンスガイド*」の「[共有設定ファイルと認証情報ファイル](https://docs.aws.amazon.com/sdkref/latest/guide/creds-config-files.html)」を参照してください。

次のサンプルコードは、`Publish` を使用する方法を説明しています。

------
#### [ .NET ]

**SDK for .NET**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/dotnetv3/SNS#code-examples)での設定と実行の方法を確認してください。
トピックへのメッセージの発行  

```
    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}");
        }
    }
```
グループ、重複、属性のオプションを指定してトピックにメッセージを発行します。  

```
    /// <summary>
    /// Publish messages using user settings.
    /// </summary>
    /// <returns>Async task.</returns>
    public static async Task PublishMessages()
    {
        Console.WriteLine("Now we can publish messages.");

        var keepSendingMessages = true;
        string? deduplicationId = null;
        string? toneAttribute = null;
        while (keepSendingMessages)
        {
            Console.WriteLine();
            var message = GetUserResponse("Enter a message to publish.", "This is a sample message");

            if (_useFifoTopic)
            {
                Console.WriteLine("Because you are using a FIFO topic, you must set a message group ID." +
                                  "\r\nAll messages within the same group will be received in the order " +
                                  "they were published.");

                Console.WriteLine();
                var messageGroupId = GetUserResponse("Enter a message group ID for this message:", "1");

                if (!_useContentBasedDeduplication)
                {
                    Console.WriteLine("Because you are not using content-based deduplication, " +
                                      "you must enter a deduplication ID.");

                    Console.WriteLine("Enter a deduplication ID for this message.");
                    deduplicationId = GetUserResponse("Enter a deduplication ID for this message.", "1");
                }

                if (GetYesNoResponse("Add an attribute to this message?"))
                {
                    Console.WriteLine("Enter a number for an attribute.");
                    for (int i = 0; i < _tones.Length; i++)
                    {
                        Console.WriteLine($"\t{i + 1}. {_tones[i]}");
                    }

                    var selection = GetUserResponse("", "1");
                    int.TryParse(selection, out var selectionNumber);

                    if (selectionNumber > 0 && selectionNumber < _tones.Length)
                    {
                        toneAttribute = _tones[selectionNumber - 1];
                    }
                }

                var messageID = await SnsWrapper.PublishToTopicWithAttribute(
                    _topicArn, message, "tone", toneAttribute, deduplicationId, messageGroupId);

                Console.WriteLine($"Message published with id {messageID}.");
            }

            keepSendingMessages = GetYesNoResponse("Send another message?", false);
        }
    }
```
ユーザーの選択を発行アクションに適用します。  

```
    /// <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 .NET API リファレンス*」の「[発行](https://docs.aws.amazon.com/goto/DotNetSDKV3/sns-2010-03-31/Publish)」を参照してください。

------
#### [ C\$1\$1 ]

**SDK for C\$1\$1**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/cpp/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
//! 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();
}
```
属性を指定してメッセージを発行します。  

```
        static const Aws::String TONE_ATTRIBUTE("tone");
        static const Aws::Vector<Aws::String> TONES = {"cheerful", "funny", "serious",
                                                       "sincere"};

        Aws::Client::ClientConfiguration clientConfig;
        // Optional: Set to the AWS Region (overrides config file).
        // clientConfig.region = "us-east-1";

    Aws::SNS::SNSClient snsClient(clientConfiguration);

        Aws::SNS::Model::PublishRequest request;
        request.SetTopicArn(topicARN);
        Aws::String message = askQuestion("Enter a message text to publish.  ");
        request.SetMessage(message);

        if (filteringMessages && askYesNoQuestion(
                "Add an attribute to this message? (y/n) ")) {
            for (size_t i = 0; i < TONES.size(); ++i) {
                std::cout << "  " << (i + 1) << ". " << TONES[i] << std::endl;
            }
            int selection = askQuestionForIntRange(
                    "Enter a number for an attribute. ",
                    1, static_cast<int>(TONES.size()));
            Aws::SNS::Model::MessageAttributeValue messageAttributeValue;
            messageAttributeValue.SetDataType("String");
            messageAttributeValue.SetStringValue(TONES[selection - 1]);
            request.AddMessageAttributes(TONE_ATTRIBUTE, messageAttributeValue);
        }

        Aws::SNS::Model::PublishOutcome outcome = snsClient.Publish(request);

        if (outcome.IsSuccess()) {
            std::cout << "Your message was successfully published." << std::endl;
        }
        else {
            std::cerr << "Error with TopicsAndQueues::Publish. "
                      << outcome.GetError().GetMessage()
                      << std::endl;

            cleanUp(topicARN,
                    queueURLS,
                    subscriptionARNS,
                    snsClient,
                    sqsClient);

            return false;
        }
```
+  API の詳細については、*AWS SDK for C\$1\$1 API リファレンス*の「[Publish](https://docs.aws.amazon.com/goto/SdkForCpp/sns-2010-03-31/Publish)」を参照してください。

------
#### [ CLI ]

**AWS CLI**  
**例 1: トピックにメッセージを発行するには**  
次の `publish` の例では、指定した Amazon SNS トピックに指定した通知を公開します。メッセージはテキストファイルから取得されたもので、改行を含めることができます。  

```
aws sns publish \
    --topic-arn "arn:aws:sns:us-west-2:123456789012:my-topic" \
    --message file://message.txt
```
`message.txt` の内容:  

```
Hello World
Second Line
```
出力:  

```
{
    "MessageId": "123a45b6-7890-12c3-45d6-111122223333"
}
```
**例 2: 電話番号に SMS メッセージを公開するには**  
次の `publish` の例では、`Hello world!` メッセージを電話番号 `+1-555-555-0100` に公開します。  

```
aws sns publish \
    --message "Hello world!" \
    --phone-number +1-555-555-0100
```
出力:  

```
{
    "MessageId": "123a45b6-7890-12c3-45d6-333322221111"
}
```
+  API の詳細については、「*AWS CLI コマンドリファレンス*」の「[Publish](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sns/publish.html)」を参照してください。

------
#### [ Go ]

**SDK for Go V2**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/gov2/workflows/topics_and_queues#code-examples)での設定と実行の方法を確認してください。

```
import (
	"context"
	"encoding/json"
	"log"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/sns"
	"github.com/aws/aws-sdk-go-v2/service/sns/types"
)

// SnsActions encapsulates the Amazon Simple Notification Service (Amazon SNS) actions
// used in the examples.
type SnsActions struct {
	SnsClient *sns.Client
}



// Publish publishes a message to an Amazon SNS topic. The message is then sent to all
// subscribers. When the topic is a FIFO topic, the message must also contain a group ID
// and, when ID-based deduplication is used, a deduplication ID. An optional key-value
// filter attribute can be specified so that the message can be filtered according to
// a filter policy.
func (actor SnsActions) Publish(ctx context.Context, topicArn string, message string, groupId string, dedupId string, filterKey string, filterValue string) error {
	publishInput := sns.PublishInput{TopicArn: aws.String(topicArn), Message: aws.String(message)}
	if groupId != "" {
		publishInput.MessageGroupId = aws.String(groupId)
	}
	if dedupId != "" {
		publishInput.MessageDeduplicationId = aws.String(dedupId)
	}
	if filterKey != "" && filterValue != "" {
		publishInput.MessageAttributes = map[string]types.MessageAttributeValue{
			filterKey: {DataType: aws.String("String"), StringValue: aws.String(filterValue)},
		}
	}
	_, err := actor.SnsClient.Publish(ctx, &publishInput)
	if err != nil {
		log.Printf("Couldn't publish message to topic %v. Here's why: %v", topicArn, err)
	}
	return err
}
```
+  API の詳細については、*AWS SDK for Go API リファレンス*の「[Publish](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/sns#Client.Publish)」を参照してください。

------
#### [ Java ]

**SDK for Java 2.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javav2/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;
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 PublishTopic {
    public static void main(String[] args) {
        final String usage = """

                Usage:    <message> <topicArn>

                Where:
                   message - The message text to send.
                   topicArn - The ARN of the topic to publish.
                """;

        if (args.length != 2) {
            System.out.println(usage);
            System.exit(1);
        }

        String message = args[0];
        String topicArn = args[1];
        SnsClient snsClient = SnsClient.builder()
                .region(Region.US_EAST_1)
                .build();
        pubTopic(snsClient, message, topicArn);
        snsClient.close();
    }

    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.x API リファレンス*の「[Publish](https://docs.aws.amazon.com/goto/SdkForJavaV2/sns-2010-03-31/Publish)」を参照してください。

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/sns#code-examples)での設定と実行の方法を確認してください。
別のモジュールでクライアントを作成し、エクスポートします。  

```
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;
};
```
グループ、重複、属性のオプションを指定してトピックにメッセージを発行します。  

```
  async publishMessages() {
    const message = await this.prompter.input({
      message: MESSAGES.publishMessagePrompt,
    });

    let groupId;
    let deduplicationId;
    let choices;

    if (this.isFifo) {
      await this.logger.log(MESSAGES.groupIdNotice);
      groupId = await this.prompter.input({
        message: MESSAGES.groupIdPrompt,
      });

      if (this.autoDedup === false) {
        await this.logger.log(MESSAGES.deduplicationIdNotice);
        deduplicationId = await this.prompter.input({
          message: MESSAGES.deduplicationIdPrompt,
        });
      }

      choices = await this.prompter.checkbox({
        message: MESSAGES.messageAttributesPrompt,
        choices: toneChoices,
      });
    }

    await this.snsClient.send(
      new PublishCommand({
        TopicArn: this.topicArn,
        Message: message,
        ...(groupId
          ? {
              MessageGroupId: groupId,
            }
          : {}),
        ...(deduplicationId
          ? {
              MessageDeduplicationId: deduplicationId,
            }
          : {}),
        ...(choices
          ? {
              MessageAttributes: {
                tone: {
                  DataType: "String.Array",
                  StringValue: JSON.stringify(choices),
                },
              },
            }
          : {}),
      }),
    );

    const publishAnother = await this.prompter.confirm({
      message: MESSAGES.publishAnother,
    });

    if (publishAnother) {
      await this.publishMessages();
    }
  }
```
+  詳細については、「[AWS SDK for JavaScript デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/sns-examples-publishing-messages.html)」を参照してください。
+  API の詳細については、AWS SDK for JavaScript API リファレンスの「[Publish](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/sns/command/PublishCommand)」を参照してください。**

------
#### [ Kotlin ]

**SDK for Kotlin**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/kotlin/services/sns#code-examples)での設定と実行の方法を確認してください。

```
suspend fun pubTopic(
    topicArnVal: String,
    messageVal: String,
) {
    val request =
        PublishRequest {
            message = messageVal
            topicArn = topicArnVal
        }

    SnsClient.fromEnvironment { region = "us-east-1" }.use { snsClient ->
        val result = snsClient.publish(request)
        println("${result.messageId} message sent.")
    }
}
```
+  API の詳細については、*AWS SDK for Kotlin API リファレンス*の「[Publish](https://sdk.amazonaws.com/kotlin/api/latest/index.html)」を参照してください。

------
#### [ PHP ]

**SDK for PHP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/php/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
require 'vendor/autoload.php';

use Aws\Exception\AwsException;
use Aws\Sns\SnsClient;


/**
 * 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 デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/sns-examples-subscribing-unsubscribing-topics.html#publish-a-message-to-an-sns-topic)」を参照してください。
+  API の詳細については、AWS SDK for PHP API リファレンスの「[Publish](https://docs.aws.amazon.com/goto/SdkForPHPV3/sns-2010-03-31/Publish)」を参照してください。**

------
#### [ PowerShell ]

**Tools for PowerShell V4**  
**例 1: この例では、インラインで宣言された単一の MessageAttribute を使用してメッセージを発行しています。**  

```
Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute @{'City'=[Amazon.SimpleNotificationService.Model.MessageAttributeValue]@{DataType='String'; StringValue ='AnyCity'}}
```
**例 2: この例では、事前に宣言された複数の MessageAttribute を使用してメッセージを発行しています。**  

```
$cityAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute $messageAttributes
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V4)*」の「[Publish](https://docs.aws.amazon.com/powershell/v4/reference)」を参照してください。

**Tools for PowerShell V5**  
**例 1: この例では、インラインで宣言された単一の MessageAttribute を使用してメッセージを発行しています。**  

```
Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute @{'City'=[Amazon.SimpleNotificationService.Model.MessageAttributeValue]@{DataType='String'; StringValue ='AnyCity'}}
```
**例 2: この例では、事前に宣言された複数の MessageAttribute を使用してメッセージを発行しています。**  

```
$cityAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$cityAttributeValue.DataType = "String"
$cityAttributeValue.StringValue = "AnyCity"

$populationAttributeValue = New-Object Amazon.SimpleNotificationService.Model.MessageAttributeValue
$populationAttributeValue.DataType = "Number"
$populationAttributeValue.StringValue = "1250800"

$messageAttributes = New-Object System.Collections.Hashtable
$messageAttributes.Add("City", $cityAttributeValue)
$messageAttributes.Add("Population", $populationAttributeValue)

Publish-SNSMessage -TopicArn "arn:aws:sns:us-west-2:123456789012:my-topic" -Message "Hello" -MessageAttribute $messageAttributes
```
+  API の詳細については、「*AWS Tools for PowerShell コマンドレットリファレンス (V5)*」の「[Publish](https://docs.aws.amazon.com/powershell/v5/reference)」を参照してください。

------
#### [ Python ]

**SDK for Python (Boto3)**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/sns#code-examples)での設定と実行の方法を確認してください。
サブスクリプションが属性に基づいてフィルター処理できるように、属性を含むメッセージを発行します。  

```
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 version of the message
        while an email subscriber could receive a longer version.

        :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
```

```
class SnsWrapper:
    """Wrapper class for managing Amazon SNS operations."""

    def __init__(self, sns_client: Any) -> None:
        """
        Initialize the SnsWrapper.

        :param sns_client: A Boto3 Amazon SNS client.
        """
        self.sns_client = sns_client

    @classmethod
    def from_client(cls) -> 'SnsWrapper':
        """
        Create an SnsWrapper instance using a default boto3 client.

        :return: An instance of this class.
        """
        sns_client = boto3.client('sns')
        return cls(sns_client)


    def publish_message(
        self,
        topic_arn: str,
        message: str,
        tone_attribute: Optional[str] = None,
        deduplication_id: Optional[str] = None,
        message_group_id: Optional[str] = None
    ) -> str:
        """
        Publish a message to an SNS topic.

        :param topic_arn: The ARN of the SNS topic.
        :param message: The message content to publish.
        :param tone_attribute: Optional tone attribute for message filtering.
        :param deduplication_id: Optional deduplication ID for FIFO topics.
        :param message_group_id: Optional message group ID for FIFO topics.
        :return: The message ID of the published message.
        :raises ClientError: If the message publication fails.
        """
        try:
            publish_args = {
                'TopicArn': topic_arn,
                'Message': message
            }

            # Add message attributes if tone is specified
            if tone_attribute:
                publish_args['MessageAttributes'] = {
                    'tone': {
                        'DataType': 'String',
                        'StringValue': tone_attribute
                    }
                }

            # Add FIFO-specific parameters
            if message_group_id:
                publish_args['MessageGroupId'] = message_group_id

            if deduplication_id:
                publish_args['MessageDeduplicationId'] = deduplication_id

            response = self.sns_client.publish(**publish_args)

            message_id = response['MessageId']
            logger.info(f"Published message to topic {topic_arn} with ID: {message_id}")
            return message_id

        except ClientError as e:
            error_code = e.response.get('Error', {}).get('Code', 'Unknown')
            logger.error(f"Error publishing message to topic: {error_code} - {e}")
            raise
```
+  API の詳細については、**「AWS SDK for Python (Boto3) API リファレンス」の「[Publish](https://docs.aws.amazon.com/goto/boto3/sns-2010-03-31/Publish)」を参照してください。

------
#### [ Ruby ]

**SDK for Ruby**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
# Service class for sending messages using Amazon Simple Notification Service (SNS)
class SnsMessageSender
  # Initializes the SnsMessageSender with an SNS client
  #
  # @param sns_client [Aws::SNS::Client] The SNS client
  def initialize(sns_client)
    @sns_client = sns_client
    @logger = Logger.new($stdout)
  end

  # Sends a message to a specified SNS topic
  #
  # @param topic_arn [String] The ARN of the SNS topic
  # @param message [String] The message to send
  # @return [Boolean] true if message was successfully sent, false otherwise
  def send_message(topic_arn, message)
    @sns_client.publish(topic_arn: topic_arn, message: message)
    @logger.info("Message sent successfully to #{topic_arn}.")
    true
  rescue Aws::SNS::Errors::ServiceError => e
    @logger.error("Error while sending the message: #{e.message}")
    false
  end
end

# Example usage:
if $PROGRAM_NAME == __FILE__
  topic_arn = 'SNS_TOPIC_ARN' # Should be replaced with a real topic ARN
  message = 'MESSAGE'         # Should be replaced with the actual message content

  sns_client = Aws::SNS::Client.new
  message_sender = SnsMessageSender.new(sns_client)

  @logger.info('Sending message.')
  unless message_sender.send_message(topic_arn, message)
    @logger.error('Message sending failed. Stopping program.')
    exit 1
  end
end
```
+  詳細については、「[AWS SDK for Ruby デベロッパーガイド](https://docs.aws.amazon.com/sdk-for-ruby/v3/developer-guide/sns-example-send-message.html)」を参照してください。
+  API の詳細については、*AWS SDK for Ruby API リファレンス*の「[発行](https://docs.aws.amazon.com/goto/SdkForRubyV3/sns-2010-03-31/Publish)」を参照してください。

------
#### [ Rust ]

**SDK for Rust**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/rustv1/examples/sns#code-examples)での設定と実行の方法を確認してください。

```
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 リファレンス*の「[発行](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.publish)」を参照してください。

------
#### [ SAP ABAP ]

**SDK for SAP ABAP**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/sap-abap/services/sns#code-examples)での設定と実行の方法を確認してください。

```
    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.
```
属性を含むメッセージをトピックに発行します。  

```
    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_topicarn = iv_topic_arn
          iv_message = iv_message
          it_messageattributes = it_msg_attrs ).
        MESSAGE 'Message with attributes published to SNS topic.' TYPE 'I'.
      CATCH /aws1/cx_snsnotfoundexception.
        MESSAGE 'Topic does not exist.' TYPE 'E'.
    ENDTRY.
```
マルチフォーマットメッセージをトピックに発行します。  

```
    " Build JSON message structure for multi-format message
    DATA(lv_json_message) = |\{ "default": "{ iv_default_message }", "sms": "{ iv_sms_message }", "email": "{ iv_email_message }" \}|.

    TRY.
        oo_result = lo_sns->publish(              " oo_result is returned for testing purposes. "
          iv_topicarn = iv_topic_arn
          iv_message = lv_json_message
          iv_subject = iv_subject
          iv_messagestructure = 'json' ).
        MESSAGE 'Multi-format 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](https://docs.aws.amazon.com/sdk-for-sap-abap/v1/api/latest/index.html)」を参照してください。

------
#### [ Swift ]

**SDK for Swift**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/swift/example_code/sns#code-examples)での設定と実行の方法を確認してください。

```
import AWSSNS

        let config = try await SNSClient.SNSClientConfiguration(region: region)
        let snsClient = SNSClient(config: config)

        let output = try await snsClient.publish(
            input: PublishInput(
                message: message,
                topicArn: arn
            )
        )

        guard let messageId = output.messageId else {
            print("No message ID received from Amazon SNS.")
            return
        }
        
        print("Published message with ID \(messageId)")
```
+  API の詳細については、「*AWS SDK for Swift API リファレンス*」の「[Publish](https://sdk.amazonaws.com/swift/api/awssns/latest/documentation/awssns/snsclient/publish(input:))」を参照してください。

------

# Amazon SNS および Amazon S3 を使用した容量の大きなメッセージを発行する
<a name="large-message-payloads"></a>

容量の大きな Amazon SNS メッセージを発行するには、[Java 用 Amazon SNS 拡張クライアントライブラリ](https://github.com/awslabs/amazon-sns-java-extended-client-lib/)または [Python 用 Amazon SNS 拡張クライアントライブラリ](https://github.com/awslabs/amazon-sns-python-extended-client-lib)を使用できます。このライブラリは、現在の最大容量 256 KB を超える、最大 2 GB までのメッセージに便利です。両方のライブラリは、実際のペイロードを Amazon S3 バケットに保存し、保存された Amazon S3 オブジェクトの参照をトピックに発行します。サブスクライブした Amazon SQS キューは、[Java 用 Amazon SQS 拡張クライアントライブラリ](https://github.com/awslabs/amazon-sqs-java-extended-client-lib)を使用し、Amazon S3 からペイロードを逆参照して取得します。Lambda などの他のエンドポイントは、[Payload Offloading Java Common Library for AWS](https://github.com/awslabs/payload-offloading-java-common-lib-for-aws) を使用し、ペイロードを逆参照して取得します。

**注記**  
Amazon SNS 拡張クライアントライブラリは、標準トピックと FIFO トピックの両方と互換性があります。

# Java 用の Amazon SNS 拡張クライアントライブラリ
<a name="extended-client-library-java"></a>

## 前提条件
<a name="prereqs-sns-extended-client-library"></a>

[Java 用 Amazon SNS 拡張クライアントライブラリ](https://github.com/awslabs/amazon-sns-java-extended-client-lib)を使用するための前提条件は以下のとおりです。
+  AWS SDK。このページの例では、Java SDK AWS を使用しています。SDK をインストールしてセットアップするには、「 *AWS SDK for Java デベロッパーガイド*[」の AWS 「 SDK for Java のセットアップ](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-install.html)」を参照してください。
+ 適切な認証情報 AWS アカウント を持つ 。を作成するには AWS アカウント、[AWS ホームページ](https://aws.amazon.com/)に移動し、** AWS アカウントの作成**を選択します。手順に従います。

  認証情報の詳細については、「 *AWS SDK for Java デベロッパーガイド*」の[「開発用の AWS 認証情報とリージョンの設定](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-credentials.html)」を参照してください。
+ Java 8 以上 
+ Java 用 Amazon SNS 拡張クライアントライブラリ ([Maven](https://maven.apache.org/) からも利用可能) 

## メッセージストレージの設定
<a name="large-message-configure-storage"></a>

Amazon SNS 拡張クライアントライブラリは、メッセージの保存と取得 AWS に のペイロードオフロード Java 共通ライブラリを使用します。以下の Amazon S3 [メッセージストレージオプション](https://github.com/awslabs/amazon-sns-java-extended-client-lib/blob/main/src/main/java/software/amazon/sns/SNSExtendedClientConfiguration.java)を設定できます。
+ **カスタムメッセージサイズのしきい値** – このサイズを超えるペイロードと属性を持つメッセージは、自動的に Amazon S3 に保存されます。
+ **`alwaysThroughS3` フラグ** – この値を `true` に設定すると、すべてのメッセージペイロードが強制的に Amazon S3 に保存されます。例:

  ```
  SNSExtendedClientConfiguration snsExtendedClientConfiguration = new
  SNSExtendedClientConfiguration() .withPayloadSupportEnabled(s3Client, BUCKET_NAME).withAlwaysThroughS3(true);
  ```
+ **カスタム KMS キー** – Amazon S3 バケットのサーバー側の暗号化に使用するキー。
+ **バケット名** – メッセージペイロードを保存するための Amazon S3 バケットの名前。

## 例: Amazon S3 に保存されたペイロードを使用して Amazon SNS にメッセージを発行する
<a name="example-s3-large-payloads"></a>

次のコード例は、以下の操作方法を示しています。
+ サンプルのトピックとキューを作成します。
+ トピックからメッセージを受信するためにキューをサブスクライブします。
+ テストメッセージを発行します。

メッセージペイロードは Amazon S3 に保存され、そのペイロードへのリファレンスが発行されます。メッセージの受信には、Amazon SQS 拡張クライアントが使用されます。

**SDK for Java 1.x**  
 GitHub には、その他のリソースもあります。用例一覧を検索し、[AWS コード例リポジトリ](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/java/example_code/sns#code-examples)での設定と実行の方法を確認してください。
容量の大きなメッセージを発行するには、Amazon SNS Extended Client Library for Java を使用します。送信するメッセージは、実際のメッセージコンテンツを含む Amazon S3 オブジェクトをリファレンスします。  

```
import com.amazon.sqs.javamessaging.AmazonSQSExtendedClient;
import com.amazon.sqs.javamessaging.ExtendedClientConfiguration;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.amazonaws.services.sns.model.CreateTopicRequest;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.SetSubscriptionAttributesRequest;
import com.amazonaws.services.sns.util.Topics;
import com.amazonaws.services.sqs.AmazonSQS;
import com.amazonaws.services.sqs.AmazonSQSClientBuilder;
import com.amazonaws.services.sqs.model.CreateQueueRequest;
import com.amazonaws.services.sqs.model.ReceiveMessageResult;
import software.amazon.sns.AmazonSNSExtendedClient;
import software.amazon.sns.SNSExtendedClientConfiguration;

public class Example {

        public static void main(String[] args) {
                final String BUCKET_NAME = "extended-client-bucket";
                final String TOPIC_NAME = "extended-client-topic";
                final String QUEUE_NAME = "extended-client-queue";
                final Regions region = Regions.DEFAULT_REGION;

                // Message threshold controls the maximum message size that will be allowed to
                // be published
                // through SNS using the extended client. Payload of messages exceeding this
                // value will be stored in
                // S3. The default value of this parameter is 256 KB which is the maximum
                // message size in SNS (and SQS).
                final int EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD = 32;

                // Initialize SNS, SQS and S3 clients
                final AmazonSNS snsClient = AmazonSNSClientBuilder.standard().withRegion(region).build();
                final AmazonSQS sqsClient = AmazonSQSClientBuilder.standard().withRegion(region).build();
                final AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(region).build();

                // Create bucket, topic, queue and subscription
                s3Client.createBucket(BUCKET_NAME);
                final String topicArn = snsClient.createTopic(
                                new CreateTopicRequest().withName(TOPIC_NAME)).getTopicArn();
                final String queueUrl = sqsClient.createQueue(
                                new CreateQueueRequest().withQueueName(QUEUE_NAME)).getQueueUrl();
                final String subscriptionArn = Topics.subscribeQueue(
                                snsClient, sqsClient, topicArn, queueUrl);

                // To read message content stored in S3 transparently through SQS extended
                // client,
                // set the RawMessageDelivery subscription attribute to TRUE
                final SetSubscriptionAttributesRequest subscriptionAttributesRequest = new SetSubscriptionAttributesRequest();
                subscriptionAttributesRequest.setSubscriptionArn(subscriptionArn);
                subscriptionAttributesRequest.setAttributeName("RawMessageDelivery");
                subscriptionAttributesRequest.setAttributeValue("TRUE");
                snsClient.setSubscriptionAttributes(subscriptionAttributesRequest);

                // Initialize SNS extended client
                // PayloadSizeThreshold triggers message content storage in S3 when the
                // threshold is exceeded
                // To store all messages content in S3, use AlwaysThroughS3 flag
                final SNSExtendedClientConfiguration snsExtendedClientConfiguration = new SNSExtendedClientConfiguration()
                                .withPayloadSupportEnabled(s3Client, BUCKET_NAME)
                                .withPayloadSizeThreshold(EXTENDED_STORAGE_MESSAGE_SIZE_THRESHOLD);
                final AmazonSNSExtendedClient snsExtendedClient = new AmazonSNSExtendedClient(snsClient,
                                snsExtendedClientConfiguration);

                // Publish message via SNS with storage in S3
                final String message = "This message is stored in S3 as it exceeds the threshold of 32 bytes set above.";
                snsExtendedClient.publish(topicArn, message);

                // Initialize SQS extended client
                final ExtendedClientConfiguration sqsExtendedClientConfiguration = new ExtendedClientConfiguration()
                                .withPayloadSupportEnabled(s3Client, BUCKET_NAME);
                final AmazonSQSExtendedClient sqsExtendedClient = new AmazonSQSExtendedClient(sqsClient,
                                sqsExtendedClientConfiguration);

                // Read the message from the queue
                final ReceiveMessageResult result = sqsExtendedClient.receiveMessage(queueUrl);
                System.out.println("Received message is " + result.getMessages().get(0).getBody());
        }
}
```

## その他のエンドポイントプロトコル
<a name="large-payloads-other-protocols"></a>

Amazon SNS と Amazon SQS ライブラリの両方で、[Payload Offloading Java Common Library for AWS](https://github.com/awslabs/payload-offloading-java-common-lib-for-aws) を使用して、Amazon S3 でメッセージペイロードを保存および取得できます。Java が有効なエンドポイント (Java で実装されている HTTPS エンドポイントなど) は、同じライブラリを使用してメッセージコンテンツを逆リファレンスできます。

のペイロードオフロード Java 共通ライブラリを使用できないエンドポイントでも、Amazon S3 に保存されているペイロードを使用してメッセージを発行 AWS できます。以下は、上記のコード例で発行された Amazon S3 リファレンスの例です。

```
[
  "software.amazon.payloadoffloading.PayloadS3Pointer",
  {
    "s3BucketName": "extended-client-bucket",
    "s3Key": "xxxx-xxxxx-xxxxx-xxxxxx"
  }
]
```

# Python 用の Amazon SNS 拡張クライアントライブラリ
<a name="extended-client-library-python"></a>

## 前提条件
<a name="prereqs-sns-extended-client-library-python"></a>

[Python 用 Amazon SNS 拡張クライアントライブラリ](https://github.com/awslabs/amazon-sns-python-extended-client-lib)を使用するための前提条件は以下のとおりです。
+  AWS SDK。このページの例では、Python SDK Boto3 AWS を使用しています。SDK をインストールして設定するには、[https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) のドキュメントを参照してください。
+ 適切な認証情報 AWS アカウント を持つ 。を作成するには AWS アカウント、[AWS ホームページ](https://aws.amazon.com/)に移動し、** AWS アカウントの作成**を選択します。手順に従います。

  認証情報については、「*AWS SDK for Python デベロッパーガイド*」の「[認証情報](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html)」を参照してください。
+ Python 3.x (または以降) および pip。
+ Python 用 Amazon SNS 拡張クライアントライブラリ ([PyPI](https://pypi.org/project/amazon-sns-extended-client/) からも利用可能) 

## メッセージストレージの設定
<a name="large-message-configure-storage-python"></a>

Amazon S3 のメッセージ保存オプションを設定するには、Boto3 Amazon SNS の [Client](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns.html#client)、[Topic](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns/topic/index.html)、[PlatformEndpoint](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns/platformendpoint/index.html) の各オブジェクトで以下の属性を使用できます。
+ **`large_payload_support`** – サイズの大きいメッセージを保存する Amazon S3 バケットの名前。
+ **`use_legacy_attribute`** – `True` の場合、すべての発行済みメッセージは、現在の予約済みメッセージ属性 (`ExtendedPayloadSize`) ではなく、レガシーの予約済みメッセージ属性 (`SQSLargePayloadSize`) を使用します。
+ **`message_size_threshold`** - メッセージを大きなメッセージバケットに保存するためのしきい値。`0` 未満または `262144` を超える値を指定することはできません。デフォルトは `262144` です。
+ **`always_through_s3`** – `True` の場合、すべてのメッセージは Amazon S3 に保存されます。デフォルトは `False` です。
+ **`s3_client`** – Amazon S3 にオブジェクトを保存するために使用する Boto3 Amazon S3 の `client` オブジェクト。Amazon S3 クライアント (Amazon S3 のカスタム設定や認証情報など) を制御する場合に使用します。以前に設定していない場合は、最初の使用時にデフォルトで `boto3.client("s3")` に設定されます。

## 例: Amazon S3 にペイロードが保存されている Amazon SNS にメッセージを発行する
<a name="example-s3-large-payloads-python"></a>

次のコード例は、以下の操作方法を示しています。
+ Amazon SNS トピックと Amazon SQS キューを作成します。
+ ポリシーを Amazon SQS キューにアタッチして、Amazon SNS トピックからメッセージを受信します。
+ トピックからメッセージを受信するためにキューをサブスクライブします。
+ Amazon SNS 拡張クライアント、トピックリソース、および PlatformEndpoint リソースを使用してテストメッセージを発行します。
+ メッセージペイロードは Amazon S3 に保存され、その参照が発行されます。
+ キューから発行したメッセージと、Amazon S3 から取得した元のメッセージを印刷します。

容量の大きなメッセージを発行するには、Java 用 Amazon SNS 拡張クライアントライブラリを使用します。送信するメッセージは、実際のメッセージコンテンツが含まれている Amazon S3 オブジェクトを参照します。

```
import boto3
from sns_extended_client import SNSExtendedClientSession
from json import loads

s3_extended_payload_bucket = "extended-client-bucket-store"  # S3 bucket with the given bucket name is a resource which is created and accessible with the given AWS credentials
TOPIC_NAME = "---TOPIC-NAME---"
QUEUE_NAME = "---QUEUE-NAME---"

def allow_sns_to_write_to_sqs(topicarn, queuearn):
    policy_document = """{{
        "Version": "2012-10-17",		 	 	 
        "Statement":[
            {{
            "Sid":"MyPolicy",
            "Effect":"Allow",
            "Principal" : {{"AWS" : "*"}},
            "Action":"SQS:SendMessage",
            "Resource": "{}",
            "Condition":{{
                "ArnEquals":{{
                "aws:SourceArn": "{}"
                }}
            }}
            }}
        ]
        }}""".format(queuearn, topicarn)

    return policy_document

def get_msg_from_s3(body,sns_extended_client):
    """Handy Helper to fetch message from S3"""
    json_msg = loads(body)
    s3_object = sns_extended_client.s3_client.get_object(
        Bucket=json_msg[1].get("s3BucketName"), Key=json_msg[1].get("s3Key")
    )
    msg = s3_object.get("Body").read().decode()
    return msg


def fetch_and_print_from_sqs(sqs, queue_url,sns_extended_client):
    sqs_msg = sqs.receive_message(
        QueueUrl=queue_url,
        AttributeNames=['All'],
        MessageAttributeNames=['All'],
        VisibilityTimeout=0,
        WaitTimeSeconds=0,
        MaxNumberOfMessages=1
    ).get("Messages")[0]
    
    message_body = sqs_msg.get("Body")
    print("Published Message: {}".format(message_body))
    print("Message Stored in S3 Bucket is: {}\n".format(get_msg_from_s3(message_body,sns_extended_client)))

    # Delete the Processed Message
    sqs.delete_message(
        QueueUrl=queue_url,
        ReceiptHandle=sqs_msg['ReceiptHandle']
    )


sns_extended_client = boto3.client("sns", region_name="us-east-1")
create_topic_response = sns_extended_client.create_topic(Name=TOPIC_NAME)
sns_topic_arn = create_topic_response.get("TopicArn")

# create and subscribe an sqs queue to the sns client
sqs = boto3.client("sqs",region_name="us-east-1")
demo_queue_url = sqs.create_queue(QueueName=QUEUE_NAME).get("QueueUrl")
sqs_queue_arn = sqs.get_queue_attributes(
    QueueUrl=demo_queue_url, AttributeNames=["QueueArn"]
)["Attributes"].get("QueueArn")

# Adding policy to SQS queue such that SNS topic can send msg to SQS queue
policy_json = allow_sns_to_write_to_sqs(sns_topic_arn, sqs_queue_arn)
response = sqs.set_queue_attributes(
    QueueUrl = demo_queue_url,
    Attributes = {
        'Policy' : policy_json
    }
)

# Set the RawMessageDelivery subscription attribute to TRUE if you want to use
# SQSExtendedClient to help with retrieving msg from S3
sns_extended_client.subscribe(TopicArn=sns_topic_arn, Protocol="sqs", 
Endpoint=sqs_queue_arn
, Attributes={"RawMessageDelivery":"true"}
)

sns_extended_client.large_payload_support = s3_extended_payload_bucket

# Change default s3_client attribute of sns_extended_client to use 'us-east-1' region
sns_extended_client.s3_client = boto3.client("s3", region_name="us-east-1")


# Below is the example that all the messages will be sent to the S3 bucket
sns_extended_client.always_through_s3 = True
sns_extended_client.publish(
    TopicArn=sns_topic_arn, Message="This message should be published to S3"
)
print("\n\nPublished using SNS extended client:")
fetch_and_print_from_sqs(sqs, demo_queue_url,sns_extended_client)  # Prints message stored in s3

# Below is the example that all the messages larger than 32 bytes will be sent to the S3 bucket
print("\nUsing decreased message size threshold:")

sns_extended_client.always_through_s3 = False
sns_extended_client.message_size_threshold = 32
sns_extended_client.publish(
    TopicArn=sns_topic_arn,
    Message="This message should be published to S3 as it exceeds the limit of the 32 bytes",
)

fetch_and_print_from_sqs(sqs, demo_queue_url,sns_extended_client)  # Prints message stored in s3


# Below is the example to publish message using the SNS.Topic resource
sns_extended_client_resource = SNSExtendedClientSession().resource(
    "sns", region_name="us-east-1"
)

topic = sns_extended_client_resource.Topic(sns_topic_arn)
topic.large_payload_support = s3_extended_payload_bucket

# Change default s3_client attribute of topic to use 'us-east-1' region
topic.s3_client = boto3.client("s3", region_name="us-east-1")

topic.always_through_s3 = True
# Can Set custom S3 Keys to be used to store objects in S3
topic.publish(
    Message="This message should be published to S3 using the topic resource",
    MessageAttributes={
        "S3Key": {
            "DataType": "String",
            "StringValue": "347c11c4-a22c-42e4-a6a2-9b5af5b76587",
        }
    },
)
print("\nPublished using Topic Resource:")
fetch_and_print_from_sqs(sqs, demo_queue_url,topic)

# Below is the example to publish message using the SNS.PlatformEndpoint resource
sns_extended_client_resource = SNSExtendedClientSession().resource(
    "sns", region_name="us-east-1"
)

platform_endpoint = sns_extended_client_resource.PlatformEndpoint(sns_topic_arn)
platform_endpoint.large_payload_support = s3_extended_payload_bucket

# Change default s3_client attribute of platform_endpoint to use 'us-east-1' region
platform_endpoint.s3_client = boto3.client("s3", region_name="us-east-1")

platform_endpoint.always_through_s3 = True
# Can Set custom S3 Keys to be used to store objects in S3
platform_endpoint.publish(
    Message="This message should be published to S3 using the PlatformEndpoint resource",
    MessageAttributes={
        "S3Key": {
            "DataType": "String",
            "StringValue": "247c11c4-a22c-42e4-a6a2-9b5af5b76587",
        }
    },
)
print("\nPublished using PlatformEndpoint Resource:")
fetch_and_print_from_sqs(sqs, demo_queue_url,platform_endpoint)
```

**出力**

```
Published using SNS extended client:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3

Using decreased message size threshold:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3 as it exceeds the limit of the 32 bytes

Published using Topic Resource:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3 using the topic resource

Published using PlatformEndpoint Resource:
Published Message: ["software.amazon.payloadoffloading.PayloadS3Pointer", {"s3BucketName": "extended-client-bucket-store", "s3Key": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}]
Message Stored in S3 Bucket is: This message should be published to S3 using the PlatformEndpoint resource
```

# Amazon SNS メッセージ属性
<a name="sns-message-attributes"></a>

Amazon SNS では、メッセージに関する構造化メタデータ項目 (タイムスタンプ、地理空間データ、署名、識別子など) を指定できるメッセージ属性の配信をサポートしています。SQS サブスクリプションの場合、[raw メッセージの配信](sns-large-payload-raw-message-delivery.md)を有効にすると、最大 10 個のメッセージ属性を送信できます。10 個を超えるメッセージ属性を送信するには、Raw メッセージの配信を無効にする必要があります。raw メッセージ配信が有効になっている Amazon SQS サブスクリプション宛てのメッセージ属性が 10 個を超えるメッセージは、クライアント側のエラーとして破棄されます。

メッセージ属性はオプションであり、メッセージ本文とは別個のものですが、同時に送信されます。受信者は、この情報を使用して、メッセージ本文を最初に処理する必要なしでメッセージを処理する方法を決定できます。

 AWS マネジメントコンソール または を使用して属性を含むメッセージを送信する方法については AWS SDK for Java、[を使用して Amazon SNS トピックにメッセージを発行するには AWS マネジメントコンソール](sns-publishing.md#sns-publishing-messages)「」チュートリアルを参照してください。

**注記**  
メッセージ属性は、メッセージ構造が JSON ではなく String である場合にのみ送信されます。

また、モバイルエンドポイント用のプッシュ通知メッセージを構築するためにメッセージ属性を使用することもできます。このシナリオでは、メッセージ属性はプッシュ通知メッセージの構築のみに使用されます。属性は、Amazon SQS エンドポイントにメッセージ属性とともにメッセージを送信する場合とは異なり、エンドポイントには配信されません。

メッセージ属性を使用して、サブスクリプションフィルターポリシーでメッセージをフィルター処理可能にすることもできます。フィルターポリシーは、トピックのサブスクリプションに適用もできます。フィルターポリシーの範囲を `MessageAttributes` (デフォルト) に設定して、フィルターポリシーを適用すると、サブスクリプションは、ポリシーが受け入れる属性を持つメッセージのみを受信します。詳細については、「[Amazon SNS メッセージフィルター処理](sns-message-filtering.md)」を参照してください。

**注記**  
メッセージ属性をフィルタリングに使用する場合、値は有効な JSON 文字列でなければなりません。これにより、メッセージ属性フィルタリングが有効になっているサブスクリプションにメッセージが確実に配信されます。

## メッセージ属性の項目および検証
<a name="SNSMessageAttributesNTV"></a>

各メッセージ属性は、次の項目で構成されています。
+ **名前** - メッセージ属性名には、A-Z、a-z、0-9、下線 (\$1)、ハイフン (-)、ピリオド (.) を使用できます。名前の先頭と末尾をピリオドにすることはできず、ピリオドを連続して使用することはできません。名前では大文字と小文字が区別され、メッセージのすべての属性名間で一意にする必要があります。名前の長さは最大 256 文字です。名前の先頭を「`AWS.`」や「`Amazon.`」(または、大文字と小文字が異なるあらゆる変化形) にすることはできません。これらのプレフィックスは Amazon Web Services で使用するために取り置かれています。
+ **型** - サポートされるメッセージ属性のデータ型は、`String`、`String.Array`、`Number`、`Binary`です。データ型のコンテンツには、メッセージ本文と同じ制限があります。詳細については「[メッセージ属性のデータ型と検証](#SNSMessageAttributes.DataTypes)」セクションを参照してください。
+ **値** - ユーザー指定のメッセージ属性値。文字列データ型の場合、値属性はメッセージ本文と同じコンテンツの制限に従う必要があります。ただし、メッセージ属性をフィルタリングに使用する場合、Amazon SNS サブスクリプションフィルターポリシーとの互換性を確保するために、値は有効な JSON 文字列であることが必要です。詳細については、『*Amazon Simple Notification Service API リファレンス*』の「[公開](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html)アクション」を参照してください。

名前、型、値を空または Null にすることはできません。さらに、メッセージ本文を空または Null にすることもできません。メッセージ属性のすべての部分 (名前、型、値を含む) は、メッセージサイズの制限に含められます。制限は 256 KB です。

## メッセージ属性のデータ型と検証
<a name="SNSMessageAttributes.DataTypes"></a>

メッセージ属性のデータ型は、メッセージ属性が Amazon SNS によって処理される方法を特定します。例えば、型が数値の場合、Amazon SNS はその属性が数値であることを検証します。

Amazon SNS は、記載されている場合を除き、すべてのエンドポイントについて、次の論理データ型をサポートしています。
+ **文字列** - 文字列は、UTF-8 バイナリエンコードされた Unicode です。コードの値のリストについては、[http://en.wikipedia.org/wiki/ASCII\$1ASCII\$1printable\$1characters](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) を参照してください。
**注記**  
サロゲート値は、メッセージ属性ではサポートされていません。例えば、サロゲート値を使用して絵文字を表すと、次のエラーが発生します: `Invalid attribute value was passed in for message attribute`。
+ **String.Array** - 複数の値を含むことができる文字列として書式設定される配列。この値は、文字列、数値、またはキーワード (`true`、`false`、`null`) とすることができます。数値型またはブール型の String.Array は引用符を必要としません。複数の String.Array 値はカンマで区切られます。

  このデータ型は AWS Lambda サブスクリプションではサポートされていません。このデータ型を Lambda エンドポイントに指定すると、`String` データ型を、Amazon SNS が Lambda に配信する JSON ペイロードに格納します。
+ **数値** - 数値は正または負の整数か、浮動小数点数です。数値には、整数、浮動小数点数、倍精度浮動小数点数が通常サポートするほとんどの値を包含できる十分な範囲と精度があります。数値は -109～109 までの値とすることができ、小数点以下 5 桁の精度を持ちます。先頭と末尾の 0 は切り捨てられます。

  このデータ型は AWS Lambda サブスクリプションではサポートされていません。このデータ型を Lambda エンドポイントに指定すると、`String` データ型を、Amazon SNS が Lambda に配信する JSON ペイロードに格納します。
+ **Binary** - Binary 型の属性には、圧縮データ、暗号化データ、イメージなど、任意のバイナリデータが保存されます。

## モバイルプッシュ通知の予約済みメッセージ属性
<a name="sns-attrib-mobile-reserved"></a>

次の表は、プッシュ通知メッセージを構築するために使用できるモバイルプッシュ通知サービスの予約済みメッセージ属性の一覧です。

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/sns/latest/dg/sns-message-attributes.html)

1 メッセージ属性が要件を満たさない場合、Apple は Amazon SNS 通知を拒否します。詳細については、Apple Developer ウェブサイトの「[APNs への通知リクエストの送信](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns)」を参照してください。

# Amazon SNS メッセージのバッチ処理
<a name="sns-batch-api-actions"></a>

## メッセージのバッチ処理とは何ですか。
<a name="what-is-message-batching"></a>

個別の `Publish` API リクエストで標準トピックまたは FIFO トピックにメッセージを発行する代わりに、Amazon SNS `PublishBatch` API を使用して、単一の API リクエストで最大 10 のメッセージを発行します。メッセージをバッチで送信すると、分散アプリケーションの接続 ([A2A メッセージング](sns-system-to-system-messaging.md)) または Amazon SNS を使用した人への通知の送信 ([A2P メッセージング](sns-user-notifications.md)) に関連するコストを最大 10 分の 1 に削減できます。Amazon SNS では、操作するリージョンに基づいて、1 秒間にトピックに発行できるメッセージの数に関するクォータがあります。API クォータの詳細については、「*AWS 全般のリファレンス*」の「[Amazon SNS エンドポイントとクォータ](https://docs.aws.amazon.com/general/latest/gr/sns.html)」のページを参照してください。

**注記**  
1 回の `PublishBatch` API 呼び出しで送信するすべてのメッセージの合計サイズは 262,144 バイト (256 KiB) を超えることはできません。  
`PublishBatch` API は、IAM ポリシーの同じ `Publish` API アクションを使用します。

## メッセージのバッチ処理はどのように機能しますか。
<a name="message-batching-how-it-works"></a>

`Publish` API を使用したメッセージの公開は、`PublishBatch` API を使用したメッセージの公開に似ています。主な違いは、`PublishBatch` API リクエストでは、各メッセージに一意のバッチ ID（最大 80 文字）を割り当てる必要があります。このようにして、Amazon SNS は、バッチ内のすべてのメッセージに対して個々の API レスポンスを返して、各メッセージが発行されたか、または障害が発生したかを確認できます。FIFO トピックに発行されるメッセージについては、一意のバッチ ID の割り当てに加えて、個々のメッセージごとに `MessageDeduplicationID` および `MessageGroupId` を含める必要があります。

## 例
<a name="message-batching-examples"></a>

**のメッセージのバッチを標準トピックに公開する**

```
// Imports
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishBatchRequest;
import software.amazon.awssdk.services.sns.model.PublishBatchRequestEntry;
import software.amazon.awssdk.services.sns.model.PublishBatchResponse;
import software.amazon.awssdk.services.sns.model.SnsException;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// Code
private static final int MAX_BATCH_SIZE = 10;

public static void publishBatchToTopic(SnsClient snsClient, String topicArn, int batchSize) {
    try {
        // Validate the batch size
        if (batchSize > MAX_BATCH_SIZE) {
            throw new IllegalArgumentException("Batch size cannot exceed " + MAX_BATCH_SIZE);
        }

        // Create the batch entries
        List<PublishBatchRequestEntry> entries = IntStream.range(0, batchSize)
                .mapToObj(i -> PublishBatchRequestEntry.builder()
                        .id("id" + i)
                        .message("message" + i)
                        .build())
                .collect(Collectors.toList());

        // Build the batch request
        PublishBatchRequest request = PublishBatchRequest.builder()
                .topicArn(topicArn)
                .publishBatchRequestEntries(entries)
                .build();

        // Publish the batch request
        PublishBatchResponse response = snsClient.publishBatch(request);

        // Handle successful messages
        response.successful().forEach(success -> {
            System.out.println("Successful Batch Id: " + success.id());
            System.out.println("Message Id: " + success.messageId());
        });

        // Handle failed messages
        response.failed().forEach(failure -> {
            System.err.println("Failed Batch Id: " + failure.id());
            System.err.println("Error Code: " + failure.code());
            System.err.println("Sender Fault: " + failure.senderFault());
            System.err.println("Error Message: " + failure.message());
        });

    } catch (SnsException e) {
        // Log and handle exceptions
        System.err.println("SNS Exception: " + e.awsErrorDetails().errorMessage());
    } catch (IllegalArgumentException e) {
        System.err.println("Validation Error: " + e.getMessage());
    }
}
```

**のメッセージのバッチを FIFO トピックに公開する**

```
// Imports
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishBatchRequest;
import software.amazon.awssdk.services.sns.model.PublishBatchRequestEntry;
import software.amazon.awssdk.services.sns.model.PublishBatchResponse;
import software.amazon.awssdk.services.sns.model.BatchResultErrorEntry;
import software.amazon.awssdk.services.sns.model.SnsException;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

// Code
private static final int MAX_BATCH_SIZE = 10;

public static void publishBatchToFifoTopic(SnsClient snsClient, String topicArn) {
    try {
        // Create the batch entries to send
        List<PublishBatchRequestEntry> entries = IntStream.range(0, MAX_BATCH_SIZE)
                .mapToObj(i -> PublishBatchRequestEntry.builder()
                        .id("id" + i)
                        .message("message" + i)
                        .messageGroupId("groupId")
                        .messageDeduplicationId("deduplicationId" + i)
                        .build())
                .collect(Collectors.toList());

        // Create the batch request
        PublishBatchRequest request = PublishBatchRequest.builder()
                .topicArn(topicArn)
                .publishBatchRequestEntries(entries)
                .build();

        // Publish the batch request
        PublishBatchResponse response = snsClient.publishBatch(request);

        // Handle the successfully sent messages
        response.successful().forEach(success -> {
            System.out.println("Batch Id for successful message: " + success.id());
            System.out.println("Message Id for successful message: " + success.messageId());
            System.out.println("Sequence Number for successful message: " + success.sequenceNumber());
        });

        // Handle the failed messages
        response.failed().forEach(failure -> {
            System.err.println("Batch Id for failed message: " + failure.id());
            System.err.println("Error Code for failed message: " + failure.code());
            System.err.println("Sender Fault for failed message: " + failure.senderFault());
            System.err.println("Failure Message for failed message: " + failure.message());
        });

    } catch (SnsException e) {
        // Handle any exceptions from the request
        System.err.println("SNS Exception: " + e.awsErrorDetails().errorMessage());
    }
}
```