AWS Lambda Using DynamoDB With Java – 使用DynamoDB与Java的AWS Lambda

最后修改: 2017年 2月 26日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

AWS Lambda is serverless computing service provided by Amazon Web Services and WS DynamoDB is a NoSQL database service also provided by Amazon.

AWS Lambda是由Amazon Web Services提供的无服务器计算服务,WS DynamoDB是同样由Amazon提供的NoSQL数据库服务。

Interestingly, DynamoDB supports both document store and key-value store and is fully managed by AWS.

有趣的是,DynamoDB同时支持文档存储和键值存储,并且完全由AWS管理。

Before we start, note that this tutorial requires a valid AWS account (you can create one here). Also, it’s a good idea to first read the AWS Lambda with Java article.

在我们开始之前,请注意本教程需要一个有效的 AWS 帐户(您可以在这里创建一个 )。此外,最好先阅读AWS Lambda with Java文章。

2. Maven Dependencies

2.Maven的依赖性

To enable lambda we need the following dependency which can be found on Maven Central:

要启用lambda,我们需要以下依赖,可以在Maven中心找到。

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-lambda-java-core</artifactId>
    <version>1.2.1</version>
</dependency>

To use different AWS resources we need the following dependency which also can also be found on Maven Central:

为了使用不同的AWS资源,我们需要以下依赖,这也可以在Maven Central上找到。

<dependency>
    <groupId>com.amazonaws</groupId>
    <artifactId>aws-lambda-java-events</artifactId>
    <version>3.11.0</version>
</dependency>

And to build the application, we’re going to use the Maven Shade Plugin:

而为了构建该应用程序,我们将使用Maven Shade Plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>3.0.0</version>
    <configuration>
        <createDependencyReducedPom>false</createDependencyReducedPom>
    </configuration>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
        </execution>
    </executions>
</plugin>

3. Lambda Code

3.兰姆达代码

There are different ways of creating handlers in a lambda application:

在lambda应用程序中,有不同的方式来创建处理程序。

  • MethodHandler
  • RequestHandler
  • RequestStreamHandler

We will use RequestHandler interface in our application. We’ll accept the PersonRequest in JSON format, and the response will be PersonResponse also in JSON format:

我们将在我们的应用程序中使用RequestHandler接口。我们将接受JSON格式的PersonRequest,响应将是PersonResponse也是JSON格式

public class PersonRequest {
    private String firstName;
    private String lastName;
    
    // standard getters and setters
}
public class PersonResponse {
    private String message;
    
    // standard getters and setters
}

Next is our entry point class which will implement RequestHandler interface as:

接下来是我们的入口类,它将实现RequestHandler接口。

public class SavePersonHandler implements RequestHandler<PersonRequest, PersonResponse> {

    private AmazonDynamoDB amazonDynamoDB;

    private String DYNAMODB_TABLE_NAME = "Person";
    private Regions REGION = Regions.US_WEST_2;

    public PersonResponse handleRequest(PersonRequest personRequest, Context context) {
        this.initDynamoDbClient();

        persistData(personRequest);

        PersonResponse personResponse = new PersonResponse();
        personResponse.setMessage("Saved Successfully!!!");
        return personResponse;
    }

    private void persistData(PersonRequest personRequest) throws ConditionalCheckFailedException {

        Map<String, AttributeValue> attributesMap = new HashMap<>();

        attributesMap.put("id", new AttributeValue(String.valueOf(personRequest.getId())));
        attributesMap.put("firstName", new AttributeValue(personRequest.getFirstName()));
        attributesMap.put("lastName", new AttributeValue(personRequest.getLastName()));
        attributesMap.put("age", new AttributeValue(String.valueOf(personRequest.getAge())));
        attributesMap.put("address", new AttributeValue(personRequest.getAddress()));

        amazonDynamoDB.putItem(DYNAMODB_TABLE_NAME, attributesMap);
    }

    private void initDynamoDbClient() {
        this.amazonDynamoDB = AmazonDynamoDBClientBuilder.standard()
            .withRegion(REGION)
            .build();
    }
}

Here when we implement the RequestHandler interface, we need to implement handleRequest() for the actual processing of the request. As for the rest of the code, we have:

在这里,当我们实现RequestHandler接口时,我们需要实现handleRequest()来进行请求的实际处理。至于代码的其余部分,我们有。

  • PersonRequest object – which will contain the request values passed in JSON format
  • Context object – used to get information from lambda execution environment
  • PersonResponse – which is the response object for the lambda request

When creating a AmazonDynamoDB object, we’ll first create a new instance of builder with all defaults set. Note that the region is mandatory.

在创建AmazonDynamoDB对象时,我们将首先创建一个新的builder实例,并设置所有的默认值。注意, region是必须的。

To add items in DynamoDB table, we’ll create a Map of key-values pairs that represent the item’s attributes and then we can use putItem(String, Map<String, AttributeValue>).

为了在DynamoDB表中添加项目,我们将创建一个代表项目属性的键值对地图,然后我们可以使用putItem(String, Map)。

We don’t need any predefined schema in DynamoDB table, we just need to define the Primary Key column name, which is “id” in our case.

我们不需要在DynamoDB表中预定义任何模式,我们只需要定义主键列名,在我们的案例中是“id”

4. Building the Deployment File

4.构建部署文件

To build the lambda application, we need to execute the following Maven command:

为了构建lambda应用程序,我们需要执行以下Maven命令。

mvn clean package shade:shade

Lambda application will be compiled and packaged into a jar file under the target folder.

Lambda应用程序将被编译并打包成目标文件夹下的jar文件。

5. Creating the DynamoDB Table

5.创建DynamoDB表

Follow these steps to create the DynamoDB table:

按照这些步骤来创建DynamoDB表。

  • Login to AWS Account
  • Click “DynamoDB” that can be located under “All Services”
  • This page will show already created DynamoDB tables (if any)
  • Click “Create Table” button
  • Provide “Table name” and “Primary Key” with its datatype as “Number”
  • Click on “Create” button
  • Table will be created

6. Creating the Lambda Function

6.创建Lambda函数

Follow these steps to create the Lambda function:

按照这些步骤来创建Lambda函数。

  • Login to AWS Account
  • Click “Lambda” that can be located under “All Services”
  • This page will show already created Lambda Function (if any) or no lambda functions are created click on “Get Started Now”
  • “Select blueprint” -> Select “Blank Function”
  • “Configure triggers” -> Click “Next” button
  • “Configure function”
    • “Name”: SavePerson
    • “Description”: Save Person to DDB
    • “Runtime”: Select “Java 8”
    • “Upload”: Click “Upload” button and select the jar file of lambda application
  • “Handler”: com.baeldung.lambda.dynamodb.SavePersonHandler
  • “Role”: Select “Create a custom role”
  • A new window will pop and will allow configuring IAM role for lambda execution and we need to add the DynamoDB grants in it. Once done, click “Allow” button
  • Click “Next” button
  • “Review”: Review the configuration
  • Click “Create function” button

7. Testing the Lambda Function

7.测试Lambda函数

Next step is to test the lambda function:

下一步是测试lambda函数。

  • Click the “Test” button
  • The “Input test event” window will be shown. Here, we’ll provide the JSON input for our request:
{
  "id": 1,
  "firstName": "John",
  "lastName": "Doe",
  "age": 30,
  "address": "United States"
}
  • Click “Save and test” or “Save” button
  • The output can be seen on “Execution result” section:
{
  "message": "Saved Successfully!!!"
}
  • We also need to check in DynamoDB that the record is persisted:
    • Go to “DynamoDB” Management Console
    • Select the table “Person”
    • Select the “Items” tab
    • Here you can see the person’s details which were being passed in request to lambda application
  • So the request is successfully processed by our lambda application

8. Conclusion

8.结论

In this quick article, we have learned how to create Lambda application with DynamoDB and Java 8. The detailed instructions should give you a head start in setting everything up.

在这篇快速文章中,我们已经学会了如何用DynamoDB和Java 8创建Lambda应用程序。详细的说明应该能让你在设置一切时有个初步的了解。

And, as always, the full source code for the example app can be found over on Github.

而且,像往常一样,可以在Github上找到该示例应用程序的完整源代码