Java 2.x용 SDK를 사용하는 Lambda 예제 - AWS SDK for Java 2.x

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Java 2.x용 SDK를 사용하는 Lambda 예제

다음 코드 예제는 AWS SDK for Java 2.x with Lambda를 사용하여 작업을 수행하고 일반적인 시나리오를 구현하는 방법을 보여줍니다.

작업은 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 작업은 개별 서비스 함수를 호출하는 방법을 보여 주며 관련 시나리오와 교차 서비스 예시에서 컨텍스트에 맞는 작업을 볼 수 있습니다.

시나리오는 동일한 서비스 내에서 여러 함수를 호출하여 특정 태스크를 수행하는 방법을 보여주는 코드 예시입니다.

각 예제에는 GitHub 컨텍스트에서 코드를 설정하고 실행하는 방법에 대한 지침을 찾을 수 있는 링크가 포함되어 있습니다.

시작하기

다음 코드 예제에서는 Lambda를 사용하여 시작하는 방법을 보여줍니다.

SDK for Java 2.x
참고

자세한 내용은 여기를 참조하십시오 GitHub. 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); } } }
  • API 세부 정보는 AWS SDK for Java 2.x API ListFunctions참조를 참조하십시오.

작업

다음 코드 예시에서는 CreateFunction을 사용하는 방법을 보여 줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다 GitHub. 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); } } }
  • API 세부 정보는 AWS SDK for Java 2.x API CreateFunction참조를 참조하십시오.

다음 코드 예시에서는 DeleteFunction을 사용하는 방법을 보여 줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다 GitHub. 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); } } }
  • API 세부 정보는 AWS SDK for Java 2.x API DeleteFunction참조를 참조하십시오.

다음 코드 예시에서는 Invoke을 사용하는 방법을 보여 줍니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다 GitHub. 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); } } }
  • API 세부 정보는 AWS SDK for Java 2.x API 참조Invoke을 참조하십시오.

시나리오

다음 코드 예제에서는 다음과 같은 작업을 수행하는 방법을 보여줍니다.

  • IAM 역할과 Lambda 함수를 생성하고 핸들러 코드를 업로드합니다.

  • 단일 파라미터로 함수를 간접적으로 호출하고 결과를 가져옵니다.

  • 함수 코드를 업데이트하고 환경 변수로 구성합니다.

  • 새 파라미터로 함수를 간접적으로 호출하고 결과를 가져옵니다. 반환된 실행 로그를 표시합니다.

  • 계정의 함수를 나열합니다.

자세한 내용은 콘솔로 Lambda 함수 생성을 참조하십시오.

SDK for Java 2.x
참고

더 많은 것이 있어요 GitHub. 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); } } }

서버리스 예제

다음 코드 예제는 RDS 데이터베이스에 연결하는 Lambda 함수를 구현하는 방법을 보여줍니다. 이 함수는 간단한 데이터베이스 요청을 하고 결과를 반환합니다.

SDK for Java 2.x
참고

더 많은 것이 있어요 GitHub. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다.

Java를 사용하여 Lambda 함수에서 Amazon RDS 데이터베이스에 연결합니다.

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

다음 코드 예제에서는 Kinesis 스트림에서 레코드를 받아 트리거된 이벤트를 수신하는 Lambda 함수를 구현하는 방법을 보여줍니다. 이 함수는 Kinesis 페이로드를 검색하고, Base64에서 디코딩하고, 레코드 콘텐츠를 로깅합니다.

SDK for Java 2.x
참고

자세한 내용은 여기를 참조하십시오. GitHub 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다.

Java를 사용하여 Lambda에서 Kinesis 이벤트를 사용합니다.

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

다음 코드 예제는 DynamoDB 스트림에서 레코드를 수신하여 트리거되는 이벤트를 수신하는 Lambda 함수를 구현하는 방법을 보여줍니다. 이 함수는 DynamoDB 페이로드를 검색하고 레코드 콘텐츠를 로깅합니다.

SDK for Java 2.x
참고

자세한 내용은 여기에서 확인할 수 있습니다. GitHub 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다.

Java를 사용하여 Lambda로 DynamoDB 이벤트 소비

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

다음 코드 예제는 S3 버킷에 객체를 업로드하여 트리거된 이벤트를 수신하는 Lambda 함수를 구현하는 방법을 보여줍니다. 해당 함수는 이벤트 파라미터에서 S3 버킷 이름과 객체 키를 검색하고 Amazon S3 API를 호출하여 객체의 콘텐츠 유형을 검색하고 로깅합니다.

SDK for Java 2.x
참고

더 많은 것이 있어요 GitHub. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다.

Java를 사용하여 Lambda로 S3 이벤트를 사용합니다.

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

다음 코드 예제에서는 SNS 주제의 메시지를 받아 트리거된 이벤트를 수신하는 Lambda 함수를 구현하는 방법을 보여줍니다. 함수는 이벤트 파라미터에서 메시지를 검색하고 각 메시지의 내용을 로깅합니다.

SDK for Java 2.x
참고

더 많은 것이 있어요 GitHub. 서버리스 예제 리포지토리에서 전체 예제를 찾아보고 설정 및 실행 방법을 알아봅니다.

Java를 사용하여 Lambda로 SNS 이벤트를 사용합니다.

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

다음 코드 예제는 SQS 대기열에서 메시지를 받아 트리거된 이벤트를 수신하는 Lambda 함수를 구현하는 방법을 보여줍니다. 함수는 이벤트 파라미터에서 메시지를 검색하고 각 메시지의 내용을 로깅합니다.

SDK for Java 2.x
참고

더 많은 것이 있어요 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.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에 신호를 보냅니다.

SDK for Java 2.x
참고

더 많은 것이 있어요 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에 신호를 보냅니다.

SDK for Java 2.x
참고

자세한 내용은 다음과 같습니다. 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에 신호를 보냅니다.

SDK for Java 2.x
참고

더 많은 것이 있어요 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); } }