Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions,
see Getting Started with Amazon Web Services in China
(PDF).
Subscribe with a filter to an Amazon SNS topic using an Amazon SDK
The following code examples show how to subscribe with a filter to an Amazon SNS topic.
Action examples are code excerpts from larger programs and must be run in context. You can see this action in
context in the following code examples:
- .NET
-
- Amazon SDK for .NET
-
Subscribe a queue to a topic with optional filters.
/// <summary>
/// Subscribe a queue to a topic with optional filters.
/// </summary>
/// <param name="topicArn">The ARN of the topic.</param>
/// <param name="useFifoTopic">The optional filtering policy for the subscription.</param>
/// <param name="queueArn">The ARN of the queue.</param>
/// <returns>The ARN of the new subscription.</returns>
public async Task<string> SubscribeTopicWithFilter(string topicArn, string? filterPolicy, string queueArn)
{
var subscribeRequest = new SubscribeRequest()
{
TopicArn = topicArn,
Protocol = "sqs",
Endpoint = queueArn
};
if (!string.IsNullOrEmpty(filterPolicy))
{
subscribeRequest.Attributes = new Dictionary<string, string> { { "FilterPolicy", filterPolicy } };
}
var subscribeResponse = await _amazonSNSClient.SubscribeAsync(subscribeRequest);
return subscribeResponse.SubscriptionArn;
}
- C++
-
- SDK for C++
-
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::SubscribeRequest request;
request.SetTopicArn(topicARN);
request.SetProtocol("sqs");
request.SetEndpoint(queueARN);
if (isFifoTopic) {
if (first) {
std::cout << "Subscriptions to a FIFO topic can have filters."
<< std::endl;
std::cout
<< "If you add a filter to this subscription, then only the filtered messages "
<< "will be received in the queue." << std::endl;
std::cout << "For information about message filtering, "
<< "see https://docs.aws.amazon.com/sns/latest/dg/sns-message-filtering.html"
<< std::endl;
std::cout << "For this example, you can filter messages by a \""
<< TONE_ATTRIBUTE << "\" attribute." << std::endl;
}
std::ostringstream ostringstream;
ostringstream << "Filter messages for \"" << queueName
<< "\"'s subscription to the topic \""
<< topicName << "\"? (y/n)";
// Add filter if user answers yes.
if (askYesNoQuestion(ostringstream.str())) {
Aws::String jsonPolicy = getFilterPolicyFromUser();
if (!jsonPolicy.empty()) {
filteringMessages = true;
std::cout << "This is the filter policy for this subscription."
<< std::endl;
std::cout << jsonPolicy << std::endl;
request.AddAttributes("FilterPolicy", jsonPolicy);
}
else {
std::cout
<< "Because you did not select any attributes, no filter "
<< "will be added to this subscription." << std::endl;
}
}
} // if (isFifoTopic)
Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request);
if (outcome.IsSuccess()) {
Aws::String subscriptionARN = outcome.GetResult().GetSubscriptionArn();
std::cout << "The queue '" << queueName
<< "' has been subscribed to the topic '"
<< "'" << topicName << "'" << std::endl;
std::cout << "with the subscription ARN '" << subscriptionARN << "."
<< std::endl;
subscriptionARNS.push_back(subscriptionARN);
}
else {
std::cerr << "Error with TopicsAndQueues::Subscribe. "
<< outcome.GetError().GetMessage()
<< std::endl;
cleanUp(topicARN,
queueURLS,
subscriptionARNS,
snsClient,
sqsClient);
return false;
}
//! Routine that lets the user select attributes for a subscription filter policy.
/*!
\sa getFilterPolicyFromUser()
\return Aws::String: The filter policy as JSON.
*/
Aws::String AwsDoc::TopicsAndQueues::getFilterPolicyFromUser() {
std::cout
<< "You can filter messages by one or more of the following \""
<< TONE_ATTRIBUTE << "\" attributes." << std::endl;
std::vector<Aws::String> filterSelections;
int selection;
do {
for (size_t j = 0; j < TONES.size(); ++j) {
std::cout << " " << (j + 1) << ". " << TONES[j]
<< std::endl;
}
selection = askQuestionForIntRange(
"Enter a number (or enter zero to stop adding more). ",
0, static_cast<int>(TONES.size()));
if (selection != 0) {
const Aws::String &selectedTone(TONES[selection - 1]);
// Add the tone to the selection if it is not already added.
if (std::find(filterSelections.begin(),
filterSelections.end(),
selectedTone)
== filterSelections.end()) {
filterSelections.push_back(selectedTone);
}
}
} while (selection != 0);
Aws::String result;
if (!filterSelections.empty()) {
std::ostringstream jsonPolicyStream;
jsonPolicyStream << "{ \"" << TONE_ATTRIBUTE << "\": [";
for (size_t j = 0; j < filterSelections.size(); ++j) {
jsonPolicyStream << "\"" << filterSelections[j] << "\"";
if (j < filterSelections.size() - 1) {
jsonPolicyStream << ",";
}
}
jsonPolicyStream << "] }";
result = jsonPolicyStream.str();
}
return result;
}
- JavaScript
-
- SDK for JavaScript (v3)
-
import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns";
const client = new SNSClient({});
export const subscribeQueueFiltered = async (
topicArn = "TOPIC_ARN",
queueArn = "QUEUE_ARN"
) => {
const command = new SubscribeCommand({
TopicArn: topicArn,
Protocol: "sqs",
Endpoint: queueArn,
Attributes: {
// This subscription will only receive messages with the 'event' attribute set to 'order_placed'.
FilterPolicyScope: "MessageAttributes",
FilterPolicy: JSON.stringify({
event: ["order_placed"],
}),
},
});
const response = await client.send(command);
console.log(response);
// {
// '$metadata': {
// httpStatusCode: 200,
// requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2',
// extendedRequestId: undefined,
// cfId: undefined,
// attempts: 1,
// totalRetryDelay: 0
// },
// SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue-test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
// }
return response;
};
For a complete list of Amazon SDK developer guides and code examples, see
Using Amazon SNS with an Amazon SDK.
This topic also includes information about getting started and details about previous SDK versions.