AWS Lambda
开发人员指南
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 AWS 服务入门

Java 中的 AWS Lambda 上下文对象

当 Lambda 运行您的函数时,它会将上下文对象传递到处理程序。此对象提供的方法和属性包含有关调用、函数和执行环境的信息。

上下文方法

  • getRemainingTimeInMillis() – Returns the number of milliseconds left before the execution times out.

  • getFunctionName() – Returns the name of the Lambda function.

  • getFunctionVersion() – Returns the version of the function.

  • getInvokedFunctionArn() – Returns the Amazon Resource Name (ARN) used to invoke the function. Indicates if the invoker specified a version number or alias.

  • getMemoryLimitInMB() – Returns the amount of memory configured on the function.

  • getAwsRequestId() – Returns the identifier of the invocation request.

  • getLogGroupName() – Returns the log group for the function.

  • getLogStreamName() – Returns the log stream for the function instance.

  • getIdentity() – (mobile apps) Returns information about the Amazon Cognito identity that authorized the request.

  • getClientContext() – (mobile apps) Returns the client context provided to the Lambda invoker by the client application.

  • getLogger() – 返回函数的记录器对象

以下示例显示记录上下文信息的处理程序函数。

例 ContextLogger.java

package example; import java.io.InputStream; import java.io.OutputStream; import com.amazonaws.services.lambda.runtime.Context; public class ContextLogger { public static void myHandler(InputStream inputStream, OutputStream outputStream, Context context) { int letter; try { while((letter = inputStream.read()) != -1) { outputStream.write(Character.toUpperCase(letter)); } Thread.sleep(3000); // Intentional delay for testing the getRemainingTimeInMillis() result. } catch (Exception e) { e.printStackTrace(); } // Print info from the context object System.out.println("Function name: " + context.getFunctionName()); System.out.println("Max mem allocated: " + context.getMemoryLimitInMB()); System.out.println("Time remaining in milliseconds: " + context.getRemainingTimeInMillis()); System.out.println("CloudWatch log stream name: " + context.getLogStreamName()); System.out.println("CloudWatch log group name: " + context.getLogGroupName()); } }

Dependencies

  • aws-lambda-java-core

Build the code with the Lambda library dependencies to create a deployment package. For instructions, see Java 中的 AWS Lambda 部署程序包.