Inscrever uma função do Lambda para receber notificações de um tópico do Amazon SNS usando um AWS SDK - Exemplos de código do SDK da AWS

Há mais exemplos de AWS SDK disponíveis no repositório AWSDoc SDK Examples GitHub .

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Inscrever uma função do Lambda para receber notificações de um tópico do Amazon SNS usando um AWS SDK

Os exemplos de código a seguir mostram como inscrever uma função do Lambda para receber notificações de um tópico do Amazon SNS.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação em contexto nos seguintes exemplos de código:

C++
SDK for C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

//! Subscribe to an Amazon Simple Notification Service (Amazon SNS) topic with delivery to an AWS Lambda function. /*! \param topicARN: The Amazon Resource Name (ARN) for an Amazon SNS topic. \param lambdaFunctionARN: The ARN for an AWS Lambda function. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::SNS::subscribeLambda(const Aws::String &topicARN, const Aws::String &lambdaFunctionARN, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::SNS::SNSClient snsClient(clientConfiguration); Aws::SNS::Model::SubscribeRequest request; request.SetTopicArn(topicARN); request.SetProtocol("lambda"); request.SetEndpoint(lambdaFunctionARN); const Aws::SNS::Model::SubscribeOutcome outcome = snsClient.Subscribe(request); if (outcome.IsSuccess()) { std::cout << "Subscribed successfully." << std::endl; std::cout << "Subscription ARN '" << outcome.GetResult().GetSubscriptionArn() << "'." << std::endl; } else { std::cerr << "Error while subscribing " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • Para obter detalhes da API, consulte Subscribe na Referência da API do AWS SDK for C++.

Java
SDK para Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

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 ""; } }
  • Para obter detalhes da API, consulte Subscribe na Referência da API do AWS SDK for Java 2.x.

JavaScript
SDK para JavaScript (v3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

Crie o cliente em um módulo separado e exporte-o.

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

Importe o SDK e os módulos do cliente e chame a API.

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function. */ export const subscribeLambda = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "lambda", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; };
Kotlin
SDK for Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

suspend fun subLambda(topicArnVal: String?, lambdaArn: String?) { val request = SubscribeRequest { protocol = "lambda" endpoint = lambdaArn returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) println(" The subscription Arn is ${result.subscriptionArn}") } }
  • Para obter detalhes da API, consulte Subscribe na Referência da API do AWS SDK for Kotlin.