SDK for Java 2.x を使用する Amazon SNS の例 - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

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

SDK for Java 2.x を使用する Amazon SNS の例

次のコードサンプルは、Amazon SNS で AWS SDK for Java 2.x を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、関連するシナリオやサービス間の例ではアクションのコンテキストが確認できます。

「シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

各例には、 へのリンクが含まれています。このリンクには GitHub、コンテキスト内でコードをセットアップして実行する方法の手順が記載されています。

開始方法

以下のコード例は、Amazon SNS の使用を開始する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

package com.example.sns; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.paginators.ListTopicsIterable; public class HelloSNS { public static void main(String[] args) { SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); listSNSTopics(snsClient); snsClient.close(); } public static void listSNSTopics(SnsClient snsClient) { try { ListTopicsIterable listTopics = snsClient.listTopicsPaginator(); listTopics.stream() .flatMap(r -> r.topics().stream()) .forEach(content -> System.out.println(" Topic ARN: " + content.topicArn())); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、「 API リファレンスListTopics」の「」を参照してください。 AWS SDK for Java 2.x

アクション

次のコード例は、Amazon SNS トピックにタグを追加する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.Tag; import software.amazon.awssdk.services.sns.model.TagResourceRequest; import java.util.ArrayList; import java.util.List; /** * 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 AddTags { public static void main(String[] args) { final String usage = """ Usage: <topicArn> Where: topicArn - The ARN of the topic to which tags are added. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); addTopicTags(snsClient, topicArn); snsClient.close(); } public static void addTopicTags(SnsClient snsClient, String topicArn) { try { Tag tag = Tag.builder() .key("Team") .value("Development") .build(); Tag tag2 = Tag.builder() .key("Environment") .value("Gamma") .build(); List<Tag> tagList = new ArrayList<>(); tagList.add(tag); tagList.add(tag2); TagResourceRequest tagResourceRequest = TagResourceRequest.builder() .resourceArn(topicArn) .tags(tagList) .build(); snsClient.tagResource(tagResourceRequest); System.out.println("Tags have been added to " + topicArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、「 API リファレンスTagResource」の「」を参照してください。 AWS SDK for Java 2.x

次のコード例は、電話番号が Amazon SNS メッセージの受信をオプトアウトしているかを確認する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CheckIfPhoneNumberIsOptedOutRequest; import software.amazon.awssdk.services.sns.model.CheckIfPhoneNumberIsOptedOutResponse; 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 CheckOptOut { public static void main(String[] args) { final String usage = """ Usage: <phoneNumber> Where: phoneNumber - The mobile phone number to look up (for example, +1XXX5550100). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String phoneNumber = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); checkPhone(snsClient, phoneNumber); snsClient.close(); } public static void checkPhone(SnsClient snsClient, String phoneNumber) { try { CheckIfPhoneNumberIsOptedOutRequest request = CheckIfPhoneNumberIsOptedOutRequest.builder() .phoneNumber(phoneNumber) .build(); CheckIfPhoneNumberIsOptedOutResponse result = snsClient.checkIfPhoneNumberIsOptedOut(request); System.out.println( result.isOptedOut() + "Phone Number " + phoneNumber + " has Opted Out of receiving sns messages." + "\n\nStatus was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、「 API リファレンスCheckIfPhoneNumberIsOptedOut」の「」を参照してください。 AWS SDK for Java 2.x

次のコード例は、以前の Subscribe アクションでエンドポイントに送信したトークンを検証することによって、エンドポイントの所有者が Amazon SNS メッセージを受信することを希望しているか確認する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.ConfirmSubscriptionRequest; import software.amazon.awssdk.services.sns.model.ConfirmSubscriptionResponse; 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 ConfirmSubscription { public static void main(String[] args) { final String usage = """ Usage: <subscriptionToken> <topicArn> Where: subscriptionToken - A short-lived token sent to an endpoint during the Subscribe action. topicArn - The ARN of the topic.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String subscriptionToken = args[0]; String topicArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); confirmSub(snsClient, subscriptionToken, topicArn); snsClient.close(); } public static void confirmSub(SnsClient snsClient, String subscriptionToken, String topicArn) { try { ConfirmSubscriptionRequest request = ConfirmSubscriptionRequest.builder() .token(subscriptionToken) .topicArn(topicArn) .build(); ConfirmSubscriptionResponse result = snsClient.confirmSubscription(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nSubscription Arn: \n\n" + result.subscriptionArn()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、「 API リファレンスConfirmSubscription」の「」を参照してください。 AWS SDK for Java 2.x

次のコード例は、Amazon SNS トピックを作成する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateTopic { public static void main(String[] args) { final String usage = """ Usage: <topicName> Where: topicName - The name of the topic to create (for example, mytopic). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicName = args[0]; System.out.println("Creating a topic with name: " + topicName); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnVal = createSNSTopic(snsClient, topicName); System.out.println("The topic ARN is" + arnVal); snsClient.close(); } public static String createSNSTopic(SnsClient snsClient, String topicName) { CreateTopicResponse result; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • API の詳細については、「 API リファレンスCreateTopic」の「」を参照してください。 AWS SDK for Java 2.x

次のコード例は、Amazon SNS サブスクリプションを削除する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.UnsubscribeRequest; import software.amazon.awssdk.services.sns.model.UnsubscribeResponse; /** * 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 Unsubscribe { public static void main(String[] args) { final String usage = """ Usage: <subscriptionArn> Where: subscriptionArn - The ARN of the subscription to delete. """; if (args.length < 1) { System.out.println(usage); System.exit(1); } String subscriptionArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); unSub(snsClient, subscriptionArn); snsClient.close(); } public static void unSub(SnsClient snsClient, String subscriptionArn) { try { UnsubscribeRequest request = UnsubscribeRequest.builder() .subscriptionArn(subscriptionArn) .build(); UnsubscribeResponse result = snsClient.unsubscribe(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nSubscription was removed for " + request.subscriptionArn()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、AWS SDK for Java 2.x API リファレンスの「Unsubscribe」を参照してください。

次のコード例は、Amazon SNS トピックとそのトピックに対するすべてのサブスクリプションを削除する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.DeleteTopicRequest; import software.amazon.awssdk.services.sns.model.DeleteTopicResponse; 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 DeleteTopic { public static void main(String[] args) { final String usage = """ Usage: <topicArn> Where: topicArn - The ARN of the topic to delete. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); System.out.println("Deleting a topic with name: " + topicArn); deleteSNSTopic(snsClient, topicArn); snsClient.close(); } public static void deleteSNSTopic(SnsClient snsClient, String topicArn) { try { DeleteTopicRequest request = DeleteTopicRequest.builder() .topicArn(topicArn) .build(); DeleteTopicResponse result = snsClient.deleteTopic(request); System.out.println("\n\nStatus was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、「 API リファレンスDeleteTopic」の「」を参照してください。 AWS SDK for Java 2.x

次のコード例は、Amazon SNS トピックのプロパティを取得する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.GetTopicAttributesRequest; import software.amazon.awssdk.services.sns.model.GetTopicAttributesResponse; 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 GetTopicAttributes { public static void main(String[] args) { final String usage = """ Usage: <topicArn> Where: topicArn - The ARN of the topic to look up. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); System.out.println("Getting attributes for a topic with name: " + topicArn); getSNSTopicAttributes(snsClient, topicArn); snsClient.close(); } public static void getSNSTopicAttributes(SnsClient snsClient, String topicArn) { try { GetTopicAttributesRequest request = GetTopicAttributesRequest.builder() .topicArn(topicArn) .build(); GetTopicAttributesResponse result = snsClient.getTopicAttributes(request); System.out.println("\n\nStatus is " + result.sdkHttpResponse().statusCode() + "\n\nAttributes: \n\n" + result.attributes()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、「 API リファレンスGetTopicAttributes」の「」を参照してください。 AWS SDK for Java 2.x

次のコード例は、Amazon SNS SMS メッセージを送信するための設定を取得する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.GetSubscriptionAttributesRequest; import software.amazon.awssdk.services.sns.model.GetSubscriptionAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.Iterator; import java.util.Map; /** * 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 GetSMSAtrributes { public static void main(String[] args) { final String usage = """ Usage: <topicArn> Where: topicArn - The ARN of the topic from which to retrieve attributes. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); getSNSAttrutes(snsClient, topicArn); snsClient.close(); } public static void getSNSAttrutes(SnsClient snsClient, String topicArn) { try { GetSubscriptionAttributesRequest request = GetSubscriptionAttributesRequest.builder() .subscriptionArn(topicArn) .build(); // Get the Subscription attributes GetSubscriptionAttributesResponse res = snsClient.getSubscriptionAttributes(request); Map<String, String> map = res.attributes(); // Iterate through the map Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); System.out.println("[Key] : " + entry.getKey() + " [Value] : " + entry.getValue()); } } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.println("\n\nStatus was good"); } }
  • API の詳細については、AWS SDK for Java 2.x API リファレンスの「GetSMSAttributes」を参照してください。

次のコードサンプルは、Amazon SNS メッセージの受信をオプトアウトした電話番号をリストする方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.ListPhoneNumbersOptedOutRequest; import software.amazon.awssdk.services.sns.model.ListPhoneNumbersOptedOutResponse; 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 ListOptOut { public static void main(String[] args) { SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); listOpts(snsClient); snsClient.close(); } public static void listOpts(SnsClient snsClient) { try { ListPhoneNumbersOptedOutRequest request = ListPhoneNumbersOptedOutRequest.builder().build(); ListPhoneNumbersOptedOutResponse result = snsClient.listPhoneNumbersOptedOut(request); System.out.println("Status is " + result.sdkHttpResponse().statusCode() + "\n\nPhone Numbers: \n\n" + result.phoneNumbers()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、「 API リファレンスListPhoneNumbersOptedOut」の「」を参照してください。 AWS SDK for Java 2.x

次のコード例は、Amazon SNS トピックのサブスクライバーのリストを取得する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.ListSubscriptionsRequest; import software.amazon.awssdk.services.sns.model.ListSubscriptionsResponse; 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 ListSubscriptions { public static void main(String[] args) { SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); listSNSSubscriptions(snsClient); snsClient.close(); } public static void listSNSSubscriptions(SnsClient snsClient) { try { ListSubscriptionsRequest request = ListSubscriptionsRequest.builder() .build(); ListSubscriptionsResponse result = snsClient.listSubscriptions(request); System.out.println(result.subscriptions()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、「 API リファレンスListSubscriptions」の「」を参照してください。 AWS SDK for Java 2.x

次のコード例は、Amazon SNS トピックを一覧表示する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.ListTopicsRequest; import software.amazon.awssdk.services.sns.model.ListTopicsResponse; 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 ListTopics { public static void main(String[] args) { SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); listSNSTopics(snsClient); snsClient.close(); } public static void listSNSTopics(SnsClient snsClient) { try { ListTopicsRequest request = ListTopicsRequest.builder() .build(); ListTopicsResponse result = snsClient.listTopics(request); System.out.println( "Status was " + result.sdkHttpResponse().statusCode() + "\n\nTopics\n\n" + result.topics()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、「 API リファレンスListTopics」の「」を参照してください。 AWS SDK for Java 2.x

次のコードサンプルは、Amazon SNS を使用して SMS メッセージを発行する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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 PublishTextSMS { public static void main(String[] args) { final String usage = """ Usage: <message> <phoneNumber> Where: message - The message text to send. phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String message = args[0]; String phoneNumber = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTextSMS(snsClient, message, phoneNumber); snsClient.close(); } public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) { try { PublishRequest request = PublishRequest.builder() .message(message) .phoneNumber(phoneNumber) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、AWS SDK for Java 2.xAPI リファレンスの「発行」を参照してください。

次のコード例は、Amazon SNS トピックにメッセージを発行する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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.xAPI リファレンスの「発行」を参照してください。

以下のコード例は、Amazon SNS フィルターポリシーを設定する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.ArrayList; /** * 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 UseMessageFilterPolicy { public static void main(String[] args) { final String usage = """ Usage: <subscriptionArn> Where: subscriptionArn - The ARN of a subscription. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String subscriptionArn = args[0]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); usePolicy(snsClient, subscriptionArn); snsClient.close(); } public static void usePolicy(SnsClient snsClient, String subscriptionArn) { try { SNSMessageFilterPolicy fp = new SNSMessageFilterPolicy(); // Add a filter policy attribute with a single value fp.addAttribute("store", "example_corp"); fp.addAttribute("event", "order_placed"); // Add a prefix attribute fp.addAttributePrefix("customer_interests", "bas"); // Add an anything-but attribute fp.addAttributeAnythingBut("customer_interests", "baseball"); // Add a filter policy attribute with a list of values ArrayList<String> attributeValues = new ArrayList<>(); attributeValues.add("rugby"); attributeValues.add("soccer"); attributeValues.add("hockey"); fp.addAttribute("customer_interests", attributeValues); // Add a numeric attribute fp.addAttribute("price_usd", "=", 0); // Add a numeric attribute with a range fp.addAttributeRange("price_usd", ">", 0, "<=", 100); // Apply the filter policy attributes to an Amazon SNS subscription fp.apply(snsClient, subscriptionArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、「 API リファレンスSetSubscriptionAttributes」の「」を参照してください。 AWS SDK for Java 2.x

次のコード例は、Amazon SNS を使用して、SMS メッセージを送信するためのデフォルト設定を設定する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SetSmsAttributesRequest; import software.amazon.awssdk.services.sns.model.SetSmsAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.HashMap; /** * 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 SetSMSAttributes { public static void main(String[] args) { HashMap<String, String> attributes = new HashMap<>(1); attributes.put("DefaultSMSType", "Transactional"); attributes.put("UsageReportS3Bucket", "janbucket"); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setSNSAttributes(snsClient, attributes); snsClient.close(); } public static void setSNSAttributes(SnsClient snsClient, HashMap<String, String> attributes) { try { SetSmsAttributesRequest request = SetSmsAttributesRequest.builder() .attributes(attributes) .build(); SetSmsAttributesResponse result = snsClient.setSMSAttributes(request); System.out.println("Set default Attributes to " + attributes + ". Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、AWS SDK for Java 2.x API リファレンスの「SetSMSAttributes」を参照してください。

次のコード例は、Amazon SNS トピック属性を設定する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SetTopicAttributesRequest; import software.amazon.awssdk.services.sns.model.SetTopicAttributesResponse; 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 SetTopicAttributes { public static void main(String[] args) { final String usage = """ Usage: <attribute> <topicArn> <value> Where: attribute - The attribute action to use. Valid parameters are: Policy | DisplayName | DeliveryPolicy . topicArn - The ARN of the topic.\s value - The value for the attribute. """; if (args.length < 3) { System.out.println(usage); System.exit(1); } String attribute = args[0]; String topicArn = args[1]; String value = args[2]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setTopAttr(snsClient, attribute, topicArn, value); snsClient.close(); } public static void setTopAttr(SnsClient snsClient, String attribute, String topicArn, String value) { try { SetTopicAttributesRequest request = SetTopicAttributesRequest.builder() .attributeName(attribute) .attributeValue(value) .topicArn(topicArn) .build(); SetTopicAttributesResponse result = snsClient.setTopicAttributes(request); System.out.println( "\n\nStatus was " + result.sdkHttpResponse().statusCode() + "\n\nTopic " + request.topicArn() + " updated " + request.attributeName() + " to " + request.attributeValue()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • API の詳細については、「 API リファレンスSetTopicAttributes」の「」を参照してください。 AWS SDK for Java 2.x

次のコード例は、Lambda 関数をサブスクライブし、Amazon SNS トピックから通知を受信するようにする方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * 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 SubscribeLambda { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <lambdaArn> Where: topicArn - The ARN of the topic to subscribe. lambdaArn - The ARN of an AWS Lambda function. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String lambdaArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnValue = subLambda(snsClient, topicArn, lambdaArn); System.out.println("Subscription ARN: " + arnValue); snsClient.close(); } public static String subLambda(SnsClient snsClient, String topicArn, String lambdaArn) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("lambda") .endpoint(lambdaArn) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); return result.subscriptionArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }
  • API の詳細については、AWS SDK for Java 2.x API リファレンスの「Subscribe」を参照してください。

次のコードサンプルは、HTTP または HTTPS エンドポイントをサブスクライブして、Amazon SNS トピックから通知を受信するようにする方法を示します。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * 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 SubscribeHTTPS { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <url> Where: topicArn - The ARN of the topic to subscribe. url - The HTTPS endpoint that you want to receive notifications. """; if (args.length < 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String url = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subHTTPS(snsClient, topicArn, url); snsClient.close(); } public static void subHTTPS(SnsClient snsClient, String topicArn, String url) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("https") .endpoint(url) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN is " + result.subscriptionArn() + "\n\n 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 リファレンスの「Subscribe」を参照してください。

次のコード例は、Amazon SNS トピックに E メールアドレスをサブスクライブする方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * 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 SubscribeEmail { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <email> Where: topicArn - The ARN of the topic to subscribe. email - The email address to use. """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String email = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subEmail(snsClient, topicArn, email); snsClient.close(); } public static void subEmail(SnsClient snsClient, String topicArn, String email) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("email") .endpoint(email) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n 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 リファレンスの「Subscribe」を参照してください。

シナリオ

次のコード例は、Amazon SNS プッシュ通知のプラットフォームエンドポイントを作成する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointRequest; import software.amazon.awssdk.services.sns.model.CreatePlatformEndpointResponse; 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 * * In addition, create a platform application using the AWS Management Console. * See this doc topic: * * https://docs.aws.amazon.com/sns/latest/dg/mobile-push-send-register.html * * Without the values created by following the previous link, this code examples * does not work. */ public class RegistrationExample { public static void main(String[] args) { final String usage = """ Usage: <token> <platformApplicationArn> Where: token - The name of the FIFO topic.\s platformApplicationArn - The ARN value of platform application. You can get this value from the AWS Management Console.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String token = args[0]; String platformApplicationArn = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); createEndpoint(snsClient, token, platformApplicationArn); } public static void createEndpoint(SnsClient snsClient, String token, String platformApplicationArn) { System.out.println("Creating platform endpoint with token " + token); try { CreatePlatformEndpointRequest endpointRequest = CreatePlatformEndpointRequest.builder() .token(token) .platformApplicationArn(platformApplicationArn) .build(); CreatePlatformEndpointResponse response = snsClient.createPlatformEndpoint(endpointRequest); System.out.println("The ARN of the endpoint is " + response.endpointArn()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

次のコード例は、FIFO Amazon SNS トピックを作成、発行する方法を示しています。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

この例では

  • 1 つの Amazon SNS FIFO トピック、2 つの Amazon SQS FIFO キュー、および 1 つの標準キューを作成します。

  • キューをトピックにサブスクライブし、メッセージをトピックに発行します。

テストでは、各キューへのメッセージの受信を検証します。完全な例では、アクセスポリシーの追加と、最後にリソースの削除も示しています。

public class PriceUpdateExample { public final static SnsClient snsClient = SnsClient.create(); public final static SqsClient sqsClient = SqsClient.create(); public static void main(String[] args) { final String usage = "\n" + "Usage: " + " <topicName> <wholesaleQueueFifoName> <retailQueueFifoName> <analyticsQueueName>\n\n" + "Where:\n" + " fifoTopicName - The name of the FIFO topic that you want to create. \n\n" + " wholesaleQueueARN - The name of a SQS FIFO queue that will be created for the wholesale consumer. \n\n" + " retailQueueARN - The name of a SQS FIFO queue that will created for the retail consumer. \n\n" + " analyticsQueueARN - The name of a SQS standard queue that will be created for the analytics consumer. \n\n"; if (args.length != 4) { System.out.println(usage); System.exit(1); } final String fifoTopicName = args[0]; final String wholeSaleQueueName = args[1]; final String retailQueueName = args[2]; final String analyticsQueueName = args[3]; // For convenience, the QueueData class holds metadata about a queue: ARN, URL, // name and type. List<QueueData> queues = List.of( new QueueData(wholeSaleQueueName, QueueType.FIFO), new QueueData(retailQueueName, QueueType.FIFO), new QueueData(analyticsQueueName, QueueType.Standard)); // Create queues. createQueues(queues); // Create a topic. String topicARN = createFIFOTopic(fifoTopicName); // Subscribe each queue to the topic. subscribeQueues(queues, topicARN); // Allow the newly created topic to send messages to the queues. addAccessPolicyToQueuesFINAL(queues, topicARN); // Publish a sample price update message with payload. publishPriceUpdate(topicARN, "{\"product\": 214, \"price\": 79.99}", "Consumables"); // Clean up resources. deleteSubscriptions(queues); deleteQueues(queues); deleteTopic(topicARN); } public static String createFIFOTopic(String topicName) { try { // Create a FIFO topic by using the SNS service client. Map<String, String> topicAttributes = Map.of( "FifoTopic", "true", "ContentBasedDeduplication", "false"); CreateTopicRequest topicRequest = CreateTopicRequest.builder() .name(topicName) .attributes(topicAttributes) .build(); CreateTopicResponse response = snsClient.createTopic(topicRequest); String topicArn = response.topicArn(); System.out.println("The topic ARN is" + topicArn); return topicArn; } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } public static void subscribeQueues(List<QueueData> queues, String topicARN) { queues.forEach(queue -> { SubscribeRequest subscribeRequest = SubscribeRequest.builder() .topicArn(topicARN) .endpoint(queue.queueARN) .protocol("sqs") .build(); // Subscribe to the endpoint by using the SNS service client. // Only Amazon SQS queues can receive notifications from an Amazon SNS FIFO // topic. SubscribeResponse subscribeResponse = snsClient.subscribe(subscribeRequest); System.out.println("The queue [" + queue.queueARN + "] subscribed to the topic [" + topicARN + "]"); queue.subscriptionARN = subscribeResponse.subscriptionArn(); }); } public static void publishPriceUpdate(String topicArn, String payload, String groupId) { try { // Create and publish a message that updates the wholesale price. String subject = "Price Update"; String dedupId = UUID.randomUUID().toString(); String attributeName = "business"; String attributeValue = "wholesale"; MessageAttributeValue msgAttValue = MessageAttributeValue.builder() .dataType("String") .stringValue(attributeValue) .build(); Map<String, MessageAttributeValue> attributes = new HashMap<>(); attributes.put(attributeName, msgAttValue); PublishRequest pubRequest = PublishRequest.builder() .topicArn(topicArn) .subject(subject) .message(payload) .messageGroupId(groupId) .messageDeduplicationId(dedupId) .messageAttributes(attributes) .build(); final PublishResponse response = snsClient.publish(pubRequest); System.out.println(response.messageId()); System.out.println(response.sequenceNumber()); System.out.println("Message was published to " + topicArn); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • API の詳細については、「AWS SDK for Java 2.x API Reference」の以下のトピックを参照してください。

次のコードの例は以下の方法を示しています。

  • Amazon SNS トピックを作成します。

  • 携帯電話番号をトピックにサブスクライブする。

  • SMS メッセージをトピックに発行して、登録されているすべての電話番号がメッセージを一度に受信できるようにします。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

トピックを作成し、その ARN を返します。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.CreateTopicRequest; import software.amazon.awssdk.services.sns.model.CreateTopicResponse; import software.amazon.awssdk.services.sns.model.SnsException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateTopic { public static void main(String[] args) { final String usage = """ Usage: <topicName> Where: topicName - The name of the topic to create (for example, mytopic). """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String topicName = args[0]; System.out.println("Creating a topic with name: " + topicName); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); String arnVal = createSNSTopic(snsClient, topicName); System.out.println("The topic ARN is" + arnVal); snsClient.close(); } public static String createSNSTopic(SnsClient snsClient, String topicName) { CreateTopicResponse result; try { CreateTopicRequest request = CreateTopicRequest.builder() .name(topicName) .build(); result = snsClient.createTopic(request); return result.topicArn(); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; } }

トピックへのエンドポイントのサブスクライブ。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SnsException; import software.amazon.awssdk.services.sns.model.SubscribeRequest; import software.amazon.awssdk.services.sns.model.SubscribeResponse; /** * 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 SubscribeTextSMS { public static void main(String[] args) { final String usage = """ Usage: <topicArn> <phoneNumber> Where: topicArn - The ARN of the topic to subscribe. phoneNumber - A mobile phone number that receives notifications (for example, +1XXX5550100). """; if (args.length < 2) { System.out.println(usage); System.exit(1); } String topicArn = args[0]; String phoneNumber = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); subTextSNS(snsClient, topicArn, phoneNumber); snsClient.close(); } public static void subTextSNS(SnsClient snsClient, String topicArn, String phoneNumber) { try { SubscribeRequest request = SubscribeRequest.builder() .protocol("sms") .endpoint(phoneNumber) .returnSubscriptionArn(true) .topicArn(topicArn) .build(); SubscribeResponse result = snsClient.subscribe(request); System.out.println("Subscription ARN: " + result.subscriptionArn() + "\n\n Status is " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

送信者の ID、上限価格、タイプなど、メッセージ上の属性を設定します。メッセージ属性はオプションです。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.sns.SnsClient; import software.amazon.awssdk.services.sns.model.SetSmsAttributesRequest; import software.amazon.awssdk.services.sns.model.SetSmsAttributesResponse; import software.amazon.awssdk.services.sns.model.SnsException; import java.util.HashMap; /** * 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 SetSMSAttributes { public static void main(String[] args) { HashMap<String, String> attributes = new HashMap<>(1); attributes.put("DefaultSMSType", "Transactional"); attributes.put("UsageReportS3Bucket", "janbucket"); SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); setSNSAttributes(snsClient, attributes); snsClient.close(); } public static void setSNSAttributes(SnsClient snsClient, HashMap<String, String> attributes) { try { SetSmsAttributesRequest request = SetSmsAttributesRequest.builder() .attributes(attributes) .build(); SetSmsAttributesResponse result = snsClient.setSMSAttributes(request); System.out.println("Set default Attributes to " + attributes + ". Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

トピックへのメッセージの発行 メッセージは、すべての受信者に送信されます。

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 PublishTextSMS { public static void main(String[] args) { final String usage = """ Usage: <message> <phoneNumber> Where: message - The message text to send. phoneNumber - The mobile phone number to which a message is sent (for example, +1XXX5550100).\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String message = args[0]; String phoneNumber = args[1]; SnsClient snsClient = SnsClient.builder() .region(Region.US_EAST_1) .build(); pubTextSMS(snsClient, message, phoneNumber); snsClient.close(); } public static void pubTextSMS(SnsClient snsClient, String message, String phoneNumber) { try { PublishRequest request = PublishRequest.builder() .message(message) .phoneNumber(phoneNumber) .build(); PublishResponse result = snsClient.publish(request); System.out .println(result.messageId() + " Message sent. Status was " + result.sdkHttpResponse().statusCode()); } catch (SnsException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

サーバーレスサンプル

次のコード例は、SNS トピックからメッセージを受信することによってトリガーされるイベントを受け取る Lambda 関数を実装する方法を示しています。この関数はイベントパラメータからメッセージを取得し、各メッセージの内容を記録します。

SDK for Java 2.x
注記

については、こちらを参照してください GitHub。サーバーレスサンプルリポジトリで完全な例を検索し、設定および実行の方法を確認してください。

Java を使用した Lambda での SNS イベントの使用。

package example; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.LambdaLogger; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SNSEvent; import com.amazonaws.services.lambda.runtime.events.SNSEvent.SNSRecord; import java.util.Iterator; import java.util.List; public class SNSEventHandler implements RequestHandler<SNSEvent, Boolean> { LambdaLogger logger; @Override public Boolean handleRequest(SNSEvent event, Context context) { logger = context.getLogger(); List<SNSRecord> records = event.getRecords(); if (!records.isEmpty()) { Iterator<SNSRecord> recordsIter = records.iterator(); while (recordsIter.hasNext()) { processRecord(recordsIter.next()); } } return Boolean.TRUE; } public void processRecord(SNSRecord record) { try { String message = record.getSNS().getMessage(); logger.log("message: " + message); } catch (Exception e) { throw new RuntimeException(e); } } }