Amazon でのサブスクリプションフィルターポリシーの適用 SNS - Amazon Simple Notification Service

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

Amazon でのサブスクリプションフィルターポリシーの適用 SNS

Amazon でのメッセージフィルタリングSNSを使用すると、フィルターポリシーに基づいてサブスクライバーにメッセージを選択的に配信できます。これらのポリシーは、サブスクリプションに配信するためにメッセージが満たす必要がある条件を定義します。raw メッセージ配信はメッセージ処理に影響を与える可能性のあるオプションですが、サブスクリプションフィルターが機能する必要はありません。

Amazon SNSコンソールを使用して、Amazon SNSサブスクリプションにフィルターポリシーを適用できます。または、プログラムでポリシーを適用するには、Amazon SNS 、 AWS Command Line Interface (AWS CLI)API、または Amazon AWS SDKをサポートする任意の を使用できますSNS。を使用することもできます AWS CloudFormation。

Raw メッセージ配信の有効化

Raw メッセージ配信により、メッセージペイロードはそのままサブスクライバーに配信され、エンコードや変換は追加されません。これは、サブスクライバーが処理に元のメッセージ形式を必要とする場合に便利です。ただし、raw メッセージ配信はサブスクリプションフィルターの機能に直接関係しません。

サブスクリプションフィルターの適用

メッセージフィルターをサブスクリプションに適用するには、JSON構文を使用してフィルターポリシーを定義します。このポリシーは、サブスクリプションに配信するためにメッセージが満たす必要がある条件を指定します。フィルターは、メッセージ属性、メッセージ構造、メッセージコンテンツなどのメッセージ属性に基づいて設定できます。

Raw メッセージ配信とサブスクリプションフィルターの関係

raw メッセージ配信を有効にすると、サブスクライバーによるメッセージの配信と処理方法に影響を与える可能性がありますが、サブスクリプションフィルターを使用するための前提条件ではありません。ただし、サブスクライバーが変更なしで元のメッセージ形式を必要とするシナリオでは、raw メッセージ配信を有効にすると、サブスクリプションフィルターと一緒に役立つ場合があります。

効果的なフィルタリングに関する考慮事項

メッセージフィルタリングを実装するときは、アプリケーションとサブスクライバーの特定の要件を考慮してください。メッセージ配信の基準に正確に一致するフィルターポリシーを定義して、効率的でターゲットを絞ったメッセージ配信を実現します。

重要

AWS IAMや Amazon などの サービスは、結果整合性と呼ばれる分散コンピューティングモデルSNSを使用します。サブスクリプションフィルターポリシーへの追加または変更は、完全に有効になるまでに最大 15 分かかります。

AWS Management Console

  1. Amazon SNSコンソール にサインインします。

  2. ナビゲーションパネルで、[サブスクリプション] を選択します。

  3. サブスクリプションを選択したら、[編集] を選択します。

  4. [Edit](編集) ページで、[Subscription filter policy](サブスクリプションフィルターポリシーセクション) を展開します。

  5. 属性ベースのフィルタリングまたはペイロードベースのフィルタリングのいずれかを選択します。

  6. JSON エディタフィールドに、フィルターポリシーのJSON本文を指定します。

  7. [変更の保存] を選択します。

    Amazon SNSは、フィルターポリシーをサブスクリプションに適用します。

AWS CLI

AWS Command Line Interface (AWS CLI) でフィルターポリシーを適用するには、次の例に示すように set-subscription-attributes コマンドを使用します。--attribute-name オプションで、FilterPolicy を指定します。には--attribute-valueJSONポリシー を指定します。

$ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute-name FilterPolicy --attribute-value '{"store":["example_corp"],"event":["order_placed"]}'

ポリシーJSONに有効な を指定するには、属性名と値を二重引用符で囲みます。また、ポリシーの引数全体を引用符で囲む必要があります。引用符のエスケープを回避するには、上記の例に示すように、一重引用符を使用してポリシーを囲み、二重引用符を使用してJSON名前と値を囲みます。

属性ベース (デフォルト) からペイロードベースのメッセージフィルタリングに切り替える場合は、 set-subscription-attributes コマンドも使用できます。--attribute-name オプションで、FilterPolicyScope を指定します。--attribute-value の場合、MessageBody を指定します。

$ aws sns set-subscription-attributes --subscription-arn arn:aws:sns: ... --attribute-name FilterPolicyScope --attribute-value MessageBody

フィルターポリシーが適用されたことを確認するには、get-subscription-attributes コマンドを使用します。ターミナル出力の属性には、以下の例に示すように、FilterPolicy キーのフィルターポリシーが表示されます。

$ aws sns get-subscription-attributes --subscription-arn arn:aws:sns: ... { "Attributes": { "Endpoint": "endpoint . . .", "Protocol": "https", "RawMessageDelivery": "false", "EffectiveDeliveryPolicy": "delivery policy . . .", "ConfirmationWasAuthenticated": "true", "FilterPolicy": "{\"store\": [\"example_corp\"], \"event\": [\"order_placed\"]}", "FilterPolicyScope": "MessageAttributes", "Owner": "111122223333", "SubscriptionArn": "arn:aws:sns: . . .", "TopicArn": "arn:aws:sns: . . ." } }

AWS SDKs

以下のコード例は、SetSubscriptionAttributes の使用方法を示しています。

重要

SDK for Java 2.x の例を使用している場合、 クラスSNSMessageFilterPolicyはすぐには使用できません。このクラスをインストールする方法については、 GitHub ウェブサイトの例を参照してください。

CLI
AWS CLI

サブスクリプション属性を設定するには

次のset-subscription-attributes例では、 RawMessageDelivery 属性をSQSサブスクリプションに設定します。

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name RawMessageDelivery \ --attribute-value true

このコマンドでは何も出力されません。

次のset-subscription-attributes例では、 FilterPolicy 属性をSQSサブスクリプションに設定します。

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{ \"anyMandatoryKey\": [\"any\", \"of\", \"these\"] }"

このコマンドでは何も出力されません。

次のset-subscription-attributes例では、SQSサブスクリプションから FilterPolicy 属性を削除します。

aws sns set-subscription-attributes \ --subscription-arn arn:aws:sns:us-east-1:123456789012:mytopic:f248de18-2cf6-578c-8592-b6f1eaa877dc \ --attribute-name FilterPolicy \ --attribute-value "{}"

このコマンドでは何も出力されません。

  • API 詳細については、「 コマンドリファレンスSetSubscriptionAttributes」の「」を参照してください。 AWS CLI

Java
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 詳細については、「 リファレンスSetSubscriptionAttributes」の「」を参照してください。 AWS SDK for Java 2.x API

Python
SDK for Python (Boto3)
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

class SnsWrapper: """Encapsulates Amazon SNS topic and subscription functions.""" def __init__(self, sns_resource): """ :param sns_resource: A Boto3 Amazon SNS resource. """ self.sns_resource = sns_resource @staticmethod def add_subscription_filter(subscription, attributes): """ Adds a filter policy to a subscription. A filter policy is a key and a list of values that are allowed. When a message is published, it must have an attribute that passes the filter or it will not be sent to the subscription. :param subscription: The subscription the filter policy is attached to. :param attributes: A dictionary of key-value pairs that define the filter. """ try: att_policy = {key: [value] for key, value in attributes.items()} subscription.set_attributes( AttributeName="FilterPolicy", AttributeValue=json.dumps(att_policy) ) logger.info("Added filter to subscription %s.", subscription.arn) except ClientError: logger.exception( "Couldn't add filter to subscription %s.", subscription.arn ) raise
  • API 詳細については、「 for Python (Boto3) リファレンスSetSubscriptionAttributes」の「」を参照してください。 AWS SDK API

Amazon SNS API

Amazon でフィルターポリシーを適用するにはAPI、 SNS SetSubscriptionAttributesアクションにリクエストを行います。AttributeName パラメータを に設定しFilterPolicyAttributeValueパラメータをフィルターポリシー に設定しますJSON。

メッセージフィルタリングを属性ベース (デフォルト) からペイロードベースのメッセージフィルタリングに切り替える場合は、SetSubscriptionAttributes アクションも使用できます。AttributeName パラメータを FilterPolicyScope に設定し、AttributeValue パラメータを MessageBody に設定します。

AWS CloudFormation

を使用してフィルターポリシーを適用するには AWS CloudFormation、 JSONまたは YAML テンプレートを使用してスタックを作成します AWS CloudFormation 。詳細については、「 AWS CloudFormation ユーザーガイド」の「 AWS::SNS::Subscriptionリソースの FilterPolicyプロパティ」とAWS CloudFormation テンプレート の例を参照してください。

  1. AWS CloudFormation コンソール にサインインします。

  2. [スタックの作成] を選択します。

  3. [テンプレートの選択] ページで、[テンプレートを Amazon S3 にアップロード] を選択してから、ファイルを選択して [次へ] をクリックします。

  4. [詳細の指定] ページで、以下の作業を行います。

    1. [スタックの名前] に「MyFilterPolicyStack」と入力します。

    2. にはmyHttpEndpoint、トピックにサブスクライブするHTTPエンドポイントを入力します。

      ヒント

      HTTP エンドポイントがない場合は、エンドポイントを作成します。

  5. [オプション] ページで、[次へ] を選択します。

  6. [Review] ページで、[作成] を選択します。