Esempi di Lambda con SDK for Java 2.x - AWS SDK for Java 2.x

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Esempi di Lambda con SDK for Java 2.x

I seguenti esempi di codice mostrano come eseguire azioni e implementare scenari comuni utilizzando AWS SDK for Java 2.x with Lambda.

Le operazioni sono estratti di codice da programmi più grandi e devono essere eseguite nel contesto. Sebbene le operazioni mostrino come richiamare le singole funzioni del servizio, è possibile visualizzarle contestualizzate negli scenari correlati e negli esempi tra servizi.

Scenari: esempi di codice che mostrano come eseguire un'attività specifica richiamando più funzioni all'interno dello stesso servizio.

Ogni esempio include un collegamento a GitHub, dove è possibile trovare istruzioni su come configurare ed eseguire il codice nel contesto.

Nozioni di base

L'esempio di codice seguente mostra come iniziare a utilizzare Lambda.

SDK per Java 2.x
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

package com.example.lambda; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.lambda.model.LambdaException; import software.amazon.awssdk.services.lambda.model.ListFunctionsResponse; import software.amazon.awssdk.services.lambda.model.FunctionConfiguration; 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 ListLambdaFunctions { public static void main(String[] args) { Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); listFunctions(awsLambda); awsLambda.close(); } public static void listFunctions(LambdaClient awsLambda) { try { ListFunctionsResponse functionResult = awsLambda.listFunctions(); List<FunctionConfiguration> list = functionResult.functions(); for (FunctionConfiguration config : list) { System.out.println("The function name is " + config.functionName()); } } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • Per i dettagli sull'API, ListFunctionsconsulta AWS SDK for Java 2.x API Reference.

Azioni

Il seguente esempio di codice mostra come utilizzareCreateFunction.

SDK per Java 2.x
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.waiters.WaiterResponse; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.services.lambda.model.CreateFunctionRequest; import software.amazon.awssdk.services.lambda.model.FunctionCode; import software.amazon.awssdk.services.lambda.model.CreateFunctionResponse; import software.amazon.awssdk.services.lambda.model.GetFunctionRequest; import software.amazon.awssdk.services.lambda.model.GetFunctionResponse; import software.amazon.awssdk.services.lambda.model.LambdaException; import software.amazon.awssdk.services.lambda.model.Runtime; import software.amazon.awssdk.services.lambda.waiters.LambdaWaiter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; /** * This code example requires a ZIP or JAR that represents the code of the * Lambda function. * If you do not have a ZIP or JAR, please refer to the following document: * * https://github.com/aws-doc-sdk-examples/tree/master/javav2/usecases/creating_workflows_stepfunctions * * Also, set up your development environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class CreateFunction { public static void main(String[] args) { final String usage = """ Usage: <functionName> <filePath> <role> <handler>\s Where: functionName - The name of the Lambda function.\s filePath - The path to the ZIP or JAR where the code is located.\s role - The role ARN that has Lambda permissions.\s handler - The fully qualified method name (for example, example.Handler::handleRequest). \s """; if (args.length != 4) { System.out.println(usage); System.exit(1); } String functionName = args[0]; String filePath = args[1]; String role = args[2]; String handler = args[3]; Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); createLambdaFunction(awsLambda, functionName, filePath, role, handler); awsLambda.close(); } public static void createLambdaFunction(LambdaClient awsLambda, String functionName, String filePath, String role, String handler) { try { LambdaWaiter waiter = awsLambda.waiter(); InputStream is = new FileInputStream(filePath); SdkBytes fileToUpload = SdkBytes.fromInputStream(is); FunctionCode code = FunctionCode.builder() .zipFile(fileToUpload) .build(); CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() .functionName(functionName) .description("Created by the Lambda Java API") .code(code) .handler(handler) .runtime(Runtime.JAVA8) .role(role) .build(); // Create a Lambda function using a waiter. CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest); GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder() .functionName(functionName) .build(); WaiterResponse<GetFunctionResponse> waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("The function ARN is " + functionResponse.functionArn()); } catch (LambdaException | FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • Per i dettagli sull'API, CreateFunctionconsulta AWS SDK for Java 2.x API Reference.

Il seguente esempio di codice mostra come utilizzareDeleteFunction.

SDK per Java 2.x
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.model.DeleteFunctionRequest; import software.amazon.awssdk.services.lambda.model.LambdaException; /** * 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 DeleteFunction { public static void main(String[] args) { final String usage = """ Usage: <functionName>\s Where: functionName - The name of the Lambda function.\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String functionName = args[0]; Region region = Region.US_EAST_1; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); deleteLambdaFunction(awsLambda, functionName); awsLambda.close(); } public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) { try { DeleteFunctionRequest request = DeleteFunctionRequest.builder() .functionName(functionName) .build(); awsLambda.deleteFunction(request); System.out.println("The " + functionName + " function was deleted"); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • Per i dettagli sull'API, DeleteFunctionconsulta AWS SDK for Java 2.x API Reference.

Il seguente esempio di codice mostra come utilizzareInvoke.

SDK per Java 2.x
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

import org.json.JSONObject; import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider; import software.amazon.awssdk.services.lambda.LambdaClient; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.lambda.model.InvokeRequest; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.services.lambda.model.InvokeResponse; import software.amazon.awssdk.services.lambda.model.LambdaException; public class LambdaInvoke { /* * Function names appear as * arn:aws:lambda:us-west-2:335556666777:function:HelloFunction * you can retrieve the value by looking at the function in the AWS Console * * Also, set up your development environment, including your credentials. * * For information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started. * html */ public static void main(String[] args) { final String usage = """ Usage: <functionName>\s Where: functionName - The name of the Lambda function\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String functionName = args[0]; Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); invokeFunction(awsLambda, functionName); awsLambda.close(); } public static void invokeFunction(LambdaClient awsLambda, String functionName) { InvokeResponse res = null; try { // Need a SdkBytes instance for the payload. JSONObject jsonObj = new JSONObject(); jsonObj.put("inputValue", "2000"); String json = jsonObj.toString(); SdkBytes payload = SdkBytes.fromUtf8String(json); // Setup an InvokeRequest. InvokeRequest request = InvokeRequest.builder() .functionName(functionName) .payload(payload) .build(); res = awsLambda.invoke(request); String value = res.payload().asUtf8String(); System.out.println(value); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } }
  • Per informazioni dettagliate sulle API, consulta Invoke nella Documentazione di riferimento delle API AWS SDK for Java 2.x .

Scenari

L'esempio di codice seguente mostra come:

  • Crea un ruolo IAM e una funzione Lambda, quindi carica il codice del gestore.

  • Richiamare la funzione con un singolo parametro e ottenere i risultati.

  • Aggiorna il codice della funzione e configuralo con una variabile di ambiente.

  • Richiamare la funzione con nuovi parametri e ottenere i risultati. Visualizza il log di esecuzione restituito.

  • Elenca le funzioni dell'account, quindi elimina le risorse.

Per ulteriori informazioni sull'utilizzo di Lambda, consulta Creare una funzione Lambda con la console.

SDK per Java 2.x
Nota

C'è dell'altro GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/* * Lambda function names appear as: * * arn:aws:lambda:us-west-2:335556666777:function:HelloFunction * * To find this value, look at the function in the AWS Management Console. * * Before running this Java code example, set up your development environment, including your credentials. * * For more information, see this documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html * * This example performs the following tasks: * * 1. Creates an AWS Lambda function. * 2. Gets a specific AWS Lambda function. * 3. Lists all Lambda functions. * 4. Invokes a Lambda function. * 5. Updates the Lambda function code and invokes it again. * 6. Updates a Lambda function's configuration value. * 7. Deletes a Lambda function. */ public class LambdaScenario { public static final String DASHES = new String(new char[80]).replace("\0", "-"); public static void main(String[] args) throws InterruptedException { final String usage = """ Usage: <functionName> <filePath> <role> <handler> <bucketName> <key>\s Where: functionName - The name of the Lambda function.\s filePath - The path to the .zip or .jar where the code is located.\s role - The AWS Identity and Access Management (IAM) service role that has Lambda permissions.\s handler - The fully qualified method name (for example, example.Handler::handleRequest).\s bucketName - The Amazon Simple Storage Service (Amazon S3) bucket name that contains the .zip or .jar used to update the Lambda function's code.\s key - The Amazon S3 key name that represents the .zip or .jar (for example, LambdaHello-1.0-SNAPSHOT.jar). """; if (args.length != 6) { System.out.println(usage); System.exit(1); } String functionName = args[0]; String filePath = args[1]; String role = args[2]; String handler = args[3]; String bucketName = args[4]; String key = args[5]; Region region = Region.US_WEST_2; LambdaClient awsLambda = LambdaClient.builder() .region(region) .build(); System.out.println(DASHES); System.out.println("Welcome to the AWS Lambda example scenario."); System.out.println(DASHES); System.out.println(DASHES); System.out.println("1. Create an AWS Lambda function."); String funArn = createLambdaFunction(awsLambda, functionName, filePath, role, handler); System.out.println("The AWS Lambda ARN is " + funArn); System.out.println(DASHES); System.out.println(DASHES); System.out.println("2. Get the " + functionName + " AWS Lambda function."); getFunction(awsLambda, functionName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("3. List all AWS Lambda functions."); listFunctions(awsLambda); System.out.println(DASHES); System.out.println(DASHES); System.out.println("4. Invoke the Lambda function."); System.out.println("*** Sleep for 1 min to get Lambda function ready."); Thread.sleep(60000); invokeFunction(awsLambda, functionName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("5. Update the Lambda function code and invoke it again."); updateFunctionCode(awsLambda, functionName, bucketName, key); System.out.println("*** Sleep for 1 min to get Lambda function ready."); Thread.sleep(60000); invokeFunction(awsLambda, functionName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("6. Update a Lambda function's configuration value."); updateFunctionConfiguration(awsLambda, functionName, handler); System.out.println(DASHES); System.out.println(DASHES); System.out.println("7. Delete the AWS Lambda function."); LambdaScenario.deleteLambdaFunction(awsLambda, functionName); System.out.println(DASHES); System.out.println(DASHES); System.out.println("The AWS Lambda scenario completed successfully"); System.out.println(DASHES); awsLambda.close(); } public static String createLambdaFunction(LambdaClient awsLambda, String functionName, String filePath, String role, String handler) { try { LambdaWaiter waiter = awsLambda.waiter(); InputStream is = new FileInputStream(filePath); SdkBytes fileToUpload = SdkBytes.fromInputStream(is); FunctionCode code = FunctionCode.builder() .zipFile(fileToUpload) .build(); CreateFunctionRequest functionRequest = CreateFunctionRequest.builder() .functionName(functionName) .description("Created by the Lambda Java API") .code(code) .handler(handler) .runtime(Runtime.JAVA8) .role(role) .build(); // Create a Lambda function using a waiter CreateFunctionResponse functionResponse = awsLambda.createFunction(functionRequest); GetFunctionRequest getFunctionRequest = GetFunctionRequest.builder() .functionName(functionName) .build(); WaiterResponse<GetFunctionResponse> waiterResponse = waiter.waitUntilFunctionExists(getFunctionRequest); waiterResponse.matched().response().ifPresent(System.out::println); return functionResponse.functionArn(); } catch (LambdaException | FileNotFoundException e) { System.err.println(e.getMessage()); System.exit(1); } return ""; } public static void getFunction(LambdaClient awsLambda, String functionName) { try { GetFunctionRequest functionRequest = GetFunctionRequest.builder() .functionName(functionName) .build(); GetFunctionResponse response = awsLambda.getFunction(functionRequest); System.out.println("The runtime of this Lambda function is " + response.configuration().runtime()); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void listFunctions(LambdaClient awsLambda) { try { ListFunctionsResponse functionResult = awsLambda.listFunctions(); List<FunctionConfiguration> list = functionResult.functions(); for (FunctionConfiguration config : list) { System.out.println("The function name is " + config.functionName()); } } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void invokeFunction(LambdaClient awsLambda, String functionName) { InvokeResponse res; try { // Need a SdkBytes instance for the payload. JSONObject jsonObj = new JSONObject(); jsonObj.put("inputValue", "2000"); String json = jsonObj.toString(); SdkBytes payload = SdkBytes.fromUtf8String(json); InvokeRequest request = InvokeRequest.builder() .functionName(functionName) .payload(payload) .build(); res = awsLambda.invoke(request); String value = res.payload().asUtf8String(); System.out.println(value); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void updateFunctionCode(LambdaClient awsLambda, String functionName, String bucketName, String key) { try { LambdaWaiter waiter = awsLambda.waiter(); UpdateFunctionCodeRequest functionCodeRequest = UpdateFunctionCodeRequest.builder() .functionName(functionName) .publish(true) .s3Bucket(bucketName) .s3Key(key) .build(); UpdateFunctionCodeResponse response = awsLambda.updateFunctionCode(functionCodeRequest); GetFunctionConfigurationRequest getFunctionConfigRequest = GetFunctionConfigurationRequest.builder() .functionName(functionName) .build(); WaiterResponse<GetFunctionConfigurationResponse> waiterResponse = waiter .waitUntilFunctionUpdated(getFunctionConfigRequest); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("The last modified value is " + response.lastModified()); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void updateFunctionConfiguration(LambdaClient awsLambda, String functionName, String handler) { try { UpdateFunctionConfigurationRequest configurationRequest = UpdateFunctionConfigurationRequest.builder() .functionName(functionName) .handler(handler) .runtime(Runtime.JAVA11) .build(); awsLambda.updateFunctionConfiguration(configurationRequest); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } public static void deleteLambdaFunction(LambdaClient awsLambda, String functionName) { try { DeleteFunctionRequest request = DeleteFunctionRequest.builder() .functionName(functionName) .build(); awsLambda.deleteFunction(request); System.out.println("The " + functionName + " function was deleted"); } catch (LambdaException e) { System.err.println(e.getMessage()); System.exit(1); } } }

Esempi serverless

Il seguente esempio di codice mostra come implementare una funzione Lambda che si connette a un database RDS. La funzione effettua una semplice richiesta al database e restituisce il risultato.

SDK per Java 2.x
Nota

C'è altro da fare GitHub. Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Connessione a un database Amazon RDS in una funzione Lambda tramite Java.

import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent; import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.rdsdata.RdsDataClient; import software.amazon.awssdk.services.rdsdata.model.ExecuteStatementRequest; import software.amazon.awssdk.services.rdsdata.model.ExecuteStatementResponse; import software.amazon.awssdk.services.rdsdata.model.Field; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class RdsLambdaHandler implements RequestHandler<APIGatewayProxyRequestEvent, APIGatewayProxyResponseEvent> { @Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent event, Context context) { APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent(); try { // Obtain auth token String token = createAuthToken(); // Define connection configuration String connectionString = String.format("jdbc:mysql://%s:%s/%s?useSSL=true&requireSSL=true", System.getenv("ProxyHostName"), System.getenv("Port"), System.getenv("DBName")); // Establish a connection to the database try (Connection connection = DriverManager.getConnection(connectionString, System.getenv("DBUserName"), token); PreparedStatement statement = connection.prepareStatement("SELECT ? + ? AS sum")) { statement.setInt(1, 3); statement.setInt(2, 2); try (ResultSet resultSet = statement.executeQuery()) { if (resultSet.next()) { int sum = resultSet.getInt("sum"); response.setStatusCode(200); response.setBody("The selected sum is: " + sum); } } } } catch (Exception e) { response.setStatusCode(500); response.setBody("Error: " + e.getMessage()); } return response; } private String createAuthToken() { // Create RDS Data Service client RdsDataClient rdsDataClient = RdsDataClient.builder() .region(Region.of(System.getenv("AWS_REGION"))) .credentialsProvider(DefaultCredentialsProvider.create()) .build(); // Define authentication request ExecuteStatementRequest request = ExecuteStatementRequest.builder() .resourceArn(System.getenv("ProxyHostName")) .secretArn(System.getenv("DBUserName")) .database(System.getenv("DBName")) .sql("SELECT 'RDS IAM Authentication'") .build(); // Execute request and obtain authentication token ExecuteStatementResponse response = rdsDataClient.executeStatement(request); Field tokenField = response.records().get(0).get(0); return tokenField.stringValue(); } }

Il seguente esempio di codice mostra come implementare una funzione Lambda che riceve un evento attivato dalla ricezione di record da un flusso Kinesis. La funzione recupera il payload Kinesis, lo decodifica da Base64 e registra il contenuto del record.

SDK per Java 2.x
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Utilizzo di un evento Kinesis con Lambda tramite Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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.KinesisEvent; public class Handler implements RequestHandler<KinesisEvent, Void> { @Override public Void handleRequest(final KinesisEvent event, final Context context) { LambdaLogger logger = context.getLogger(); if (event.getRecords().isEmpty()) { logger.log("Empty Kinesis Event received"); return null; } for (KinesisEvent.KinesisEventRecord record : event.getRecords()) { try { logger.log("Processed Event with EventId: "+record.getEventID()); String data = new String(record.getKinesis().getData().array()); logger.log("Data:"+ data); // TODO: Do interesting work based on the new data } catch (Exception ex) { logger.log("An error occurred:"+ex.getMessage()); throw ex; } } logger.log("Successfully processed:"+event.getRecords().size()+" records"); return null; } }

Il seguente esempio di codice mostra come implementare una funzione Lambda che riceve un evento attivato dalla ricezione di record da un flusso DynamoDB. La funzione recupera il payload DynamoDB e registra il contenuto del record.

SDK per Java 2.x
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Consumo di un evento DynamoDB con Lambda utilizzando Java.

import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; import com.amazonaws.services.lambda.runtime.events.DynamodbEvent.DynamodbStreamRecord; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class example implements RequestHandler<DynamodbEvent, Void> { private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); @Override public Void handleRequest(DynamodbEvent event, Context context) { System.out.println(GSON.toJson(event)); event.getRecords().forEach(this::logDynamoDBRecord); return null; } private void logDynamoDBRecord(DynamodbStreamRecord record) { System.out.println(record.getEventID()); System.out.println(record.getEventName()); System.out.println("DynamoDB Record: " + GSON.toJson(record.getDynamodb())); } }

Il seguente esempio di codice mostra come implementare una funzione Lambda che riceve un evento attivato dal caricamento di un oggetto in un bucket S3. La funzione recupera il nome del bucket S3 e la chiave dell'oggetto dal parametro evento e chiama l'API Amazon S3 per recuperare e registrare il tipo di contenuto dell'oggetto.

SDK per Java 2.x
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Utilizzo di un evento S3 con Lambda tramite Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package example; import software.amazon.awssdk.services.s3.model.HeadObjectRequest; import software.amazon.awssdk.services.s3.model.HeadObjectResponse; import software.amazon.awssdk.services.s3.S3Client; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.S3Event; import com.amazonaws.services.lambda.runtime.events.models.s3.S3EventNotification.S3EventNotificationRecord; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Handler implements RequestHandler<S3Event, String> { private static final Logger logger = LoggerFactory.getLogger(Handler.class); @Override public String handleRequest(S3Event s3event, Context context) { try { S3EventNotificationRecord record = s3event.getRecords().get(0); String srcBucket = record.getS3().getBucket().getName(); String srcKey = record.getS3().getObject().getUrlDecodedKey(); S3Client s3Client = S3Client.builder().build(); HeadObjectResponse headObject = getHeadObject(s3Client, srcBucket, srcKey); logger.info("Successfully retrieved " + srcBucket + "/" + srcKey + " of type " + headObject.contentType()); return "Ok"; } catch (Exception e) { throw new RuntimeException(e); } } private HeadObjectResponse getHeadObject(S3Client s3Client, String bucket, String key) { HeadObjectRequest headObjectRequest = HeadObjectRequest.builder() .bucket(bucket) .key(key) .build(); return s3Client.headObject(headObjectRequest); } }

Il seguente esempio di codice mostra come implementare una funzione Lambda che riceve un evento attivato dalla ricezione di messaggi da un argomento SNS. La funzione recupera i messaggi dal parametro dell'evento e registra il contenuto di ogni messaggio.

SDK per Java 2.x
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Consumo di un evento SNS con Lambda utilizzando Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 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); } } }

Il seguente esempio di codice mostra come implementare una funzione Lambda che riceve un evento attivato dalla ricezione di messaggi da una coda SQS. La funzione recupera i messaggi dal parametro dell'evento e registra il contenuto di ogni messaggio.

SDK per Java 2.x
Nota

C'è altro su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Utilizzo di un evento SQS con Lambda tramite Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage; public class Function implements RequestHandler<SQSEvent, Void> { @Override public Void handleRequest(SQSEvent sqsEvent, Context context) { for (SQSMessage msg : sqsEvent.getRecords()) { processMessage(msg, context); } context.getLogger().log("done"); return null; } private void processMessage(SQSMessage msg, Context context) { try { context.getLogger().log("Processed message " + msg.getBody()); // TODO: Do interesting work based on the new message } catch (Exception e) { context.getLogger().log("An error occurred"); throw e; } } }

Il seguente esempio di codice mostra come implementare una risposta batch parziale per le funzioni Lambda che ricevono eventi da un flusso Kinesis. La funzione riporta gli errori degli elementi batch nella risposta, segnalando a Lambda di riprovare tali messaggi in un secondo momento.

SDK per Java 2.x
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Segnalazione di errori di elementi batch di Kinesis con Lambda tramite Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.KinesisEvent; import com.amazonaws.services.lambda.runtime.events.StreamsEventResponse; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ProcessKinesisRecords implements RequestHandler<KinesisEvent, StreamsEventResponse> { @Override public StreamsEventResponse handleRequest(KinesisEvent input, Context context) { List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new ArrayList<>(); String curRecordSequenceNumber = ""; for (KinesisEvent.KinesisEventRecord kinesisEventRecord : input.getRecords()) { try { //Process your record KinesisEvent.Record kinesisRecord = kinesisEventRecord.getKinesis(); curRecordSequenceNumber = kinesisRecord.getSequenceNumber(); } catch (Exception e) { /* Since we are working with streams, we can return the failed item immediately. Lambda will immediately begin to retry processing from this failed item onwards. */ batchItemFailures.add(new StreamsEventResponse.BatchItemFailure(curRecordSequenceNumber)); return new StreamsEventResponse(batchItemFailures); } } return new StreamsEventResponse(batchItemFailures); } }

Il seguente esempio di codice mostra come implementare una risposta batch parziale per le funzioni Lambda che ricevono eventi da un flusso DynamoDB. La funzione riporta gli errori degli elementi batch nella risposta, segnalando a Lambda di riprovare tali messaggi in un secondo momento.

SDK per Java 2.x
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Segnalazione degli errori degli elementi batch di DynamoDB con Lambda utilizzando Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.DynamodbEvent; import com.amazonaws.services.lambda.runtime.events.StreamsEventResponse; import com.amazonaws.services.lambda.runtime.events.models.dynamodb.StreamRecord; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ProcessDynamodbRecords implements RequestHandler<DynamodbEvent, Serializable> { @Override public StreamsEventResponse handleRequest(DynamodbEvent input, Context context) { List<StreamsEventResponse.BatchItemFailure> batchItemFailures = new ArrayList<>(); String curRecordSequenceNumber = ""; for (DynamodbEvent.DynamodbStreamRecord dynamodbStreamRecord : input.getRecords()) { try { //Process your record StreamRecord dynamodbRecord = dynamodbStreamRecord.getDynamodb(); curRecordSequenceNumber = dynamodbRecord.getSequenceNumber(); } catch (Exception e) { /* Since we are working with streams, we can return the failed item immediately. Lambda will immediately begin to retry processing from this failed item onwards. */ batchItemFailures.add(new StreamsEventResponse.BatchItemFailure(curRecordSequenceNumber)); return new StreamsEventResponse(batchItemFailures); } } return new StreamsEventResponse(); } }

Il seguente esempio di codice mostra come implementare una risposta batch parziale per le funzioni Lambda che ricevono eventi da una coda SQS. La funzione riporta gli errori degli elementi batch nella risposta, segnalando a Lambda di riprovare tali messaggi in un secondo momento.

SDK per Java 2.x
Nota

C'è di più su. GitHub Trova l'esempio completo e scopri come eseguire la configurazione e l'esecuzione nel repository di Esempi serverless.

Segnalazione di errori di elementi batch di SQS con Lambda tramite Java.

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.events.SQSEvent; import com.amazonaws.services.lambda.runtime.events.SQSBatchResponse; import java.util.ArrayList; import java.util.List; public class ProcessSQSMessageBatch implements RequestHandler<SQSEvent, SQSBatchResponse> { @Override public SQSBatchResponse handleRequest(SQSEvent sqsEvent, Context context) { List<SQSBatchResponse.BatchItemFailure> batchItemFailures = new ArrayList<SQSBatchResponse.BatchItemFailure>(); String messageId = ""; for (SQSEvent.SQSMessage message : sqsEvent.getRecords()) { try { //process your message messageId = message.getMessageId(); } catch (Exception e) { //Add failed message identifier to the batchItemFailures list batchItemFailures.add(new SQSBatchResponse.BatchItemFailure(messageId)); } } return new SQSBatchResponse(batchItemFailures); } }