

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

# 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 Management Console
<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. **Type**에서 속성 유형(예:**String.Array**)을 선택합니다.
**참고**  
속성 유형 **String.Array**에 대해 배열을 대괄호로 묶습니다(`[]`). 배열 안에서는 문자열 값을 큰따옴표로 묶습니다. 숫자 또는 키워드 `true`, `false` 및 `null`에는 따옴표가 필요 없습니다.

   1. 속성 **Name**(예: `customer_interests`)을 입력합니다.

   1. 속성 **Value**(예: `["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 참조*의 [Publish](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: 이 예제에서는 여러 MessageAttributes가 미리 선언된 메시지를 게시하는 것을 보여줍니다.**  

```
$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 Cmdlet 참조(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: 이 예제에서는 여러 MessageAttributes가 미리 선언된 메시지를 게시하는 것을 보여줍니다.**  

```
$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 Cmdlet 참조(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 참조*의 [Publish](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 참조*의 [Publish](https://docs.rs/aws-sdk-sns/latest/aws_sdk_sns/client/struct.Client.html#method.publish)을 참조하세요.

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

**SDK for SAP ABAP API**  
 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에 대한 세부 정보는 *SAP ABAP용AWS SDK 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 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)를 사용할 수 있습니다. 이 라이브러리는 현재 최대값인 256KB(최대 2GB)보다 큰 메시지에 유용합니다. 모든 라이브러리는 실제 페이로드를 Amazon S3 버킷에 저장하고 저장된 Amazon S3 객체의 참조를 Amazon SNS 주제에 게시합니다. 구독한 Amazon SQS 대기열은 [Java용 Amazon SQS 확장 클라이언트 라이브러리](https://github.com/awslabs/amazon-sqs-java-extended-client-lib)를 사용하여 Amazon S3에서 페이로드를 역참조하고 검색할 수 있습니다. Lambda와 같은 다른 엔드포인트는 [AWS용 페이로드 오프로딩 Java 공통 라이브러리](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. 이 페이지의 예제에서는 AWS Java SDK를 사용합니다. SDK를 설치하고 설정하려면 *AWS SDK for Java 개발자 안내서*[의 Java용 AWS SDK 설정을](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/setup-install.html) 참조하세요.
+ 적절한 자격 증명이 AWS 계정 있는 . 를 생성하려면 [AWS 홈 페이지로](https://aws.amazon.com/) AWS 계정이동한 다음 ** 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 확장 클라이언트는 메시지를 수신하는 데 사용됩니다.

**Java 1.x용 SDK**  
 GitHub에 더 많은 내용이 있습니다. [AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/java/example_code/sns#code-examples)에서 전체 예를 찾고 설정 및 실행하는 방법을 배워보세요.
대용량 메시지를 게시하려면 Java용 Amazon SNS 확장 클라이언트 라이브러리를 사용하세요. 보내는 메시지는 실제 메시지 내용이 포함된 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 라이브러리는 모두 [AWS용 페이로드 오프로딩 Java 공통 라이브러리](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. 이 페이지의 예제에서는 AWS Python SDK Boto3를 사용합니다. 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 홈 페이지로](https://aws.amazon.com/) AWS 계정이동한 다음 ** AWS 계정 생성을** 선택합니다. 지침을 따릅니다.

  자격 증명에 대한 자세한 내용은 *Python용AWS SDK 개발자 안내서*에서 [자격 증명](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>

아래 속성은 Boto3 Amazon SNS [클라이언트](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sns.html#client), [주제](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) 객체에서 사용할 수 있어 Amazon S3 메시지 스토리지 옵션을 구성할 수 있습니다.
+ **`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에 `client` 객체를 저장하는 데 사용되는 Boto3 Amazon S3 객체입니다. 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에서 검색된 원본 메시지와 함께 인쇄합니다.

대용량 메시지를 게시하려면 Python용 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 구독의 경우 [원시 메시지 전송](sns-large-payload-raw-message-delivery.md)이 사용된다면 최대 10개의 메시지 속성을 보낼 수 있습니다. 10개가 넘는 메시지 속성을 보내려면 원시 메시지 전송을 사용 중지해야 합니다. 원시 메시지 전송이 활성화된 Amazon SQS 구독으로 전달되는 메시지 속성이 10개를 초과하는 메시지는 클라이언트 측 오류로 삭제됩니다.

메시지 속성은 선택 사항이며 메시지 본문과 분리되지만 함께 전송됩니다. 수신자는 이 정보를 사용하여 메시지 본문을 먼저 처리할 필요 없이 메시지를 처리하는 방법을 결정할 수 있습니다.

 AWS Management Console 또는를 사용하여 속성이 있는 메시지를 보내는 방법에 대한 자세한 내용은 [를 사용하여 Amazon SNS 주제에 메시지를 게시하려면 AWS Management Console](sns-publishing.md#sns-publishing-messages) 자습서를 AWS SDK for Java참조하세요.

**참고**  
메시지 구조가 문자열이고 JSON이 아닌 경우에만 메시지 속성이 전송됩니다.

메시지 속성을 사용하여 모바일 엔드포인트에 대한 푸시 알림 메시지를 구성할 수도 있습니다. 이 시나리오에서 메시지 속성은 푸시 알림 메시지를 구성하는 데만 사용됩니다. 이 속성은 메시지 속성이 있는 메시지를 Amazon SQS 엔드포인트에 전송할 때와 같이 엔드포인트에 제공되지 않습니다.

메시지 속성을 사용하여 구독 필터 정책으로 메시지를 필터링할 수 있도록 만들 수 있습니다. 주제 구독에 필터 정책을 적용할 수 있습니다. `MessageAttributes`(기본)로 설정된 필터 정책 범위로 필터 정책이 적용되면 구독은 정책이 수락하는 속성을 가진 메시지만 수신합니다. 자세한 내용은 [Amazon SNS 메시지 필터링](sns-message-filtering.md) 단원을 참조하십시오.

**참고**  
메시지 속성을 필터링에 사용하는 경우 값은 유효한 JSON 문자열이어야 합니다. 이렇게 하면 메시지가 메시지 속성 필터링이 활성화된 구독으로 전달됩니다.

## 메시지 속성 항목 및 유효성 검사
<a name="SNSMessageAttributesNTV"></a>

각 메시지 속성은 다음 항목으로 구성됩니다.
+ **Name** – 메시지 속성 이름에는 A-Z, a-z, 0-9, 밑줄(\$1), 하이픈(-) 및 마침표(.)와 같은 문자가 포함될 수 있습니다. 이름은 마침표로 시작하거나 끝나서는 안 되며 연속 마침표가 있으면 안 됩니다. 이름은 대소문자를 구별하며 메시지에 대한 모든 속성 이름 중에서 고유해야 합니다. 이름은 최대 256자일 수 있습니다. 이름은 `AWS.` 또는 `Amazon.`(또는 모든 대소문자 변형)으로 시작할 수 없습니다. 이러한 접두사는 Amazon Web Services에서 사용하도록 예약되어 있기 때문입니다.
+ **Type** – 지원되는 메시지 속성 데이터 형식은 `String`, `String.Array`, `Number` 및 `Binary`입니다. 데이터 형식은 내용에 대해 메시지 본문과 동일한 제한 사항이 있습니다. 자세한 정보는 [메시지 속성 데이터 형식 및 유효성 검사](#SNSMessageAttributes.DataTypes) 섹션을 참조하세요.
+ **Value** – 사용자가 지정한 메시지 속성 값입니다. 문자열 데이터 유형의 경우 값 속성은 메시지 본문과 동일한 내용 제한을 따라야 합니다. 그러나 메시지 속성을 필터링에 사용하는 경우 Amazon SNS 구독 필터 정책과의 호환성을 보장하려면 값이 유효한 JSON 문자열이어야 합니다. 자세한 정보는 *Amazon Simple Notification Service API 참조*의 [게시](https://docs.aws.amazon.com/sns/latest/api/API_Publish.html) 작업을 참조하세요.

이름, 형식 및 값이 비어 있거나 널이면 안 됩니다. 또한 메시지 본문도 비어 있거나 널이면 안 됩니다. 이름, 형식 및 값을 포함하여 메시지 속성의 모든 부분은 256KB인 메시지 크기 제한에 포함됩니다.

## 메시지 속성 데이터 형식 및 유효성 검사
<a name="SNSMessageAttributes.DataTypes"></a>

메시지 속성 데이터 형식은 메시지 속성 값이 Amazon SNS에서 처리되는 방식을 식별합니다. 예를 들어, 형식이 숫자이면 Amazon SNS는 값이 숫자인지 확인합니다.

Amazon SNS는 명시된 경우를 제외하고 모든 엔드포인트에 대해 다음 논리적 데이터 유형을 지원합니다.
+ **String** – 문자열은 UTF-8 이진 인코딩을 사용하는 유니코드입니다. 코드 값 목록은 [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 엔드포인트에 대해 이 데이터 유형을 지정하면 Amazon SNS가 Lambda에 전달하는 JSON 페이로드의 `String` 데이터 유형으로 전달됩니다.
+ **Number** – 숫자는 양수 또는 음수 정수이거나 부동 소수점 숫자입니다. 숫자는 정수, 부동 소수점 수 및 실수가 일반적으로 지원하는 가능한 대부분의 값을 포함할 수 있는 충분한 범위와 정밀도를 갖추고 있습니다. 숫자 값은 -109에서 109까지 가능하며, 정확도는 소수점 이하 5자리입니다. 앞과 끝의 0은 잘립니다.

  구독에는이 데이터 유형이 지원되지 않습니다 AWS Lambda . Lambda 엔드포인트에 대해 이 데이터 유형을 지정하면 Amazon SNS가 Lambda에 전달하는 JSON 페이로드의 `String` 데이터 유형으로 전달됩니다.
+ **Binary** – 이전 형식 속성은 모든 이진 데이터를 저장할 수 있습니다(예: 압축된 데이터, 암호화된 데이터 또는 이미지).

## 모바일 푸시 알림에 예약된 메시지 속성
<a name="sns-attrib-mobile-reserved"></a>

다음 표에서는 푸시 알림 메시지를 구성하는 데 사용할 수 있는 모바일 푸시 알림 서비스에 예약된 메시지 속성을 나열합니다.

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

1 메시지 속성이 요구 사항을 충족하지 않는 경우 Apple은 Amazon SNS 알림을 거부합니다. 자세한 내용은 Apple 개발자 웹 사이트에서 [APN에 알림 요청 보내기](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개의 메시지를 게시할 수 있습니다. 메시지를 배치로 전송하면 Amazon SNS를 통해 분산 애플리케이션 연결([A2A 메시징](sns-system-to-system-messaging.md)) 또는 사람에게 알림 전송([A2P 메시징](sns-user-notifications.md))과 관련된 비용을 최대 10배까지 줄일 수 있습니다. Amazon SNS에는 사용자가 운영 중인 리전에 따라 주제에 초당 게시할 수 있는 메시지 수에 대한 할당량이 있습니다. API 할당량에 대한 자세한 내용은 **AWS 일반 참조 가이드의 [Amazon SNS 엔드포인트 및 할당량](https://docs.aws.amazon.com/general/latest/gr/sns.html) 페이지를 참조하세요.

**참고**  
단일 `PublishBatch` API 요청에서 전송하는 전체 메시지의 총 크기 합계는 262,144바이트(256KiB)를 초과할 수 없습니다.  
이 `PublishBatch` API는 IAM 정책에 대해 동일한 `Publish` API 작업을 사용합니다.

## 메시지 배치 처리는 어떻게 작동합니까?
<a name="message-batching-how-it-works"></a>

`PublishBatch` API를 사용하여 메시지를 게시하는 것은 `Publish` API를 사용하여 메시지를 게시하는 것과 유사합니다. 주된 차이점은 `PublishBatch` API 요청 내의 각 메시지에 고유한 배치 ID(최대 80자)가 할당되어야 한다는 것입니다. 이러한 방식으로 Amazon SNS는 배치 내의 모든 메시지에 대해 개별 API 응답을 반환하여 각 메시지가 게시되었는지 또는 오류가 발생했는지 확인할 수 있습니다. FIFO 주제에 게시되는 메시지의 경우 고유한 배치 ID 할당을 포함하는 것 외에도 각 개별 메시지에 대해 `MessageDeduplicationID` 및 `MessageGroupId`를 포함해야 합니다.

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

**표준 주제에 10개의 메시지 배치 게시**

```
// 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 주제에 10개의 메시지 배치 게시**

```
// 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());
    }
}
```