使用 SDK for Java 2.x 的 SDK 的 Lambda 示例 - Amazon SDK for Java 2.x
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 SDK for Java 2.x 的 SDK 的 Lambda 示例

以下代码示例向您展示了如何使用 with Lambda 来执行操作和实现常见场景。 Amazon SDK for Java 2.x

操作是大型程序的代码摘录,必须在上下文中运行。您可以通过操作了解如何调用单个服务函数,还可以通过函数相关场景和跨服务示例的上下文查看操作。

场景 是展示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。

每个示例都包含一个指向的链接 GitHub,您可以在其中找到有关如何在上下文中设置和运行代码的说明。

开始使用

以下代码示例演示了如何开始使用 Lambda。

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考ListFunctions中的。

操作

以下代码示例演示了如何使用 CreateFunction

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考CreateFunction中的。

以下代码示例演示了如何使用 DeleteFunction

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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); } } }
  • 有关 API 的详细信息,请参阅 Amazon SDK for Java 2.x API 参考DeleteFunction中的。

以下代码示例演示了如何使用 Invoke

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

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); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 Invoke

场景

以下代码示例展示了如何:

  • 创建 IAM 角色和 Lambda 函数,然后上传处理程序代码。

  • 使用单个参数来调用函数并获取结果。

  • 更新函数代码并使用环境变量进行配置。

  • 使用新参数来调用函数并获取结果。显示返回的执行日志。

  • 列出账户函数,然后清除函数。

有关更多信息,请参阅使用控制台创建 Lambda 函数

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在 Amazon 代码示例存储库中查找完整示例,了解如何进行设置和运行。

/* * 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); } } }

无服务器示例

以下代码示例展示了如何实现一个 Lambda 函数,该函数接收因接收来自 Kinesis 流的记录而触发的事件。该函数检索 Kinesis 有效负载,将 Base64 解码,并记录下记录内容。

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

使用 Java 将 Kinesis 事件与 Lambda 结合使用。

// 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; } }

以下代码示例展示了如何实现一个 Lambda 函数,该函数接收通过将对象上传到 S3 桶而触发的事件。该函数从事件参数中检索 S3 存储桶名称和对象密钥,并调用 Amazon S3 API 来检索和记录对象的内容类型。

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

使用 Java 将 S3 事件与 Lambda 结合使用。

// 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); } }

以下代码示例展示了如何实现一个 Lambda 函数,该函数接收因接收来自 SNS 主题的消息而触发的事件。该函数从事件参数检索消息并记录每条消息的内容。

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

通过 Java 将 SNS 事件与 Lambda 结合使用。

// 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); } } }

以下代码示例展示了如何实现一个 Lambda 函数,该函数接收因接收来自 SNS 队列的消息而触发的事件。该函数从事件参数检索消息并记录每条消息的内容。

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

通过 Java 将 SQS 事件与 Lambda 结合使用。

// 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; } } }

以下代码示例展示了如何为接收来自 Kinesis 流的事件的 Lambda 函数实现部分批处理响应。该函数在响应中报告批处理项目失败,并指示 Lambda 稍后重试这些消息。

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

报告使用 Java 进行 Lambda Kinesis 批处理项目失败。

// 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); } }

以下代码示例演示如何为接收来自 DynamoDB 流的事件的 Lambda 函数实现部分批量响应。该函数在响应中报告批处理项目失败,并指示 Lambda 稍后重试这些消息。

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

报告使用 Java 通过 Lambda 进行 DynamoDB 批处理项目失败。

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

以下代码示例展示了如何为接收来自 SQS 队列的事件的 Lambda 函数实现部分批处理响应。该函数在响应中报告批处理项目失败,并指示 Lambda 稍后重试这些消息。

适用于 Java 2.x 的 SDK
注意

还有更多相关信息 GitHub。在无服务器示例存储库中查找完整示例,并了解如何进行设置和运行。

报告使用 Java 进行 Lambda SQS 批处理项目失败。

// 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); } }