1. Introduction

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

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.

2. Maven Dependencies

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

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

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

<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

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 int id;
    private String firstName;
    private String lastName;
    private int age;
    private String address;

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

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

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

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

We don’t need any predefined schema in the 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

The 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” which can be located under “All Services”
  • This page will show DynamoDB Dashboard
  • Click the “Tables” link
  • This page will show already created DynamoDB tables (if any)
  • Click the “Create table” button
  • Provide “Table name” as “Person” and “Partition key” as “id” with its datatype as “Number”
  • Click on the “Create table” button
  • The table will be created

6. Creating the Lambda Function

Follow these steps to create the Lambda function:

  • Login to AWS Account
  • Click “Lambda” which can be located under “All Services”
  • This page will show already created Lambda Functions (if any)
  • Click the “Create function” button
  • Select the “Author from scratch” option
  • Provide “Function name” as “SavePerson” and “Runtime” as “Java 8 on Amazon Linux 2” and “Architecture” as “x86_64”
  • In “Execution role” select “Use an existing role”. Select the IAM role created for lambda execution. Ensure the role has DynamoDB grants in it.
  • Click on “Create function”
  • This page will show the newly created “SavePerson” function
  • Under the “Code” tab
    • In the “Code source” section click on the “Upload from” button
    • From the dropdown select “.zip or .jar file” and upload the jar file of the lambda application
    • In the “Runtime settings” section click on the “Edit” button
    • This page will show the Runtime settings. Here change the “Handler” to “com.baeldung.lambda.dynamodb.SavePersonHandler” and click on “Save”
  • The message “Successfully updated the function SavePerson.” will appear

7. Testing the Lambda Function

The next step is to test the lambda function:

  • Click the “Test” tab
  • Provide “Event name” as “TestEvent”
  • In the “Event JSON” window provide the below JSON input :
{
  "id": 1,
  "firstName": "John",
  "lastName": "Doe",
  "age": 30,
  "address": "United States"
}
  • Click the “Test button
  • The below output will be displayed on the screen:
{
  "message": "Saved Successfully!!!"
}
  • We also need to check in DynamoDB that the record is persisted:
    • Go to “DynamoDB” Management Console
    • Click on “Tables”
    • Select the table “Person”
    • Click on the “Explore table items” tab
    • Under “Items returned” you can see the person’s details which were being passed in request to the lambda application
  • So the request is successfully processed by our lambda application

8. Conclusion

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

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

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are closed on this article!