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

最后修改: 2017年 2月 26日

1. Introduction


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.


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


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



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

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


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

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


3. Lambda Code


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


  • 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:


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:


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) {


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

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:


  • 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.


4. Building the Deployment File


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


mvn clean package shade:shade

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


5. Creating the DynamoDB Table


Follow these steps to create the DynamoDB table:


  • 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


Follow these steps to create the Lambda function:


  • 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


Next step is to test the lambda function:


  • 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


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.