Connect your Micro Service (Spring Boot Application) to AWS DynamoDB

Teja Swaroop Mylavarapu
Level Up Coding
Published in
8 min readAug 2, 2020

--

Spring Boot + DynmoDB is a good combination depending on the use case, with one being the de facto framework for Java and the other being the Next Gen NoSQL database in the AWS world.

In this article, I am going to talk about:

  1. Addressing Prerequisites — Setup your AWS Account, CLI on your Terminal.
  2. Create a DynamoDB Table on AWS Console and add a sample value.
  3. Setup the Java Spring Boot Micro Service on your local using Spring Initializr.
  4. Integrate the DynamoDB code into your Java Application using AWS SDK and successfully read the sample value.

1. Addressing Prerequisites — Setup your AWS Account, CLI on your Terminal.

Let’s first address the pre-requisites

  1. Get the Access Key ID and Secret Access Key from AWS Account
  2. Install AWS CLI on your local machine
  3. Configure AWS credentials for the AWS Account on your machine

Get the Access Key ID and Secret Access Key from AWS Account

Go to https://aws.amazon.com/console/ and login to the AWS Console. Navigate to IAM section->Dashboard->Manage Security Credentials → AccessKeys Tab and extract your Access Key ID and Secret Access Key.

Go ahead and Create on if you don’t have one.

Install AWS CLI on your local machine

After jotting down the keys, let’s install AWS CLI v2 on your system. If you already have this configured, please proceed to Step 3 where we create the AWS Infra.

Install AWS CLI by following the commands mentioned in the AWS documentation.

After installing AWS CLI, go to your mac Terminal and type in aws and that should list something like the image below. This confirms and validates that AWS CLI has been successfully configured.

Configure AWS credentials for the AWS Account on your machine

Now, time to map your AWS Credentials on your local machine. We need to configure the Access Key ID and Secret Access Key on your machine so that you can connect to yourAWS Account from your machine and create and disrupt the Infra using AWS CLI.

aws configure should do the trick and ask for the Credentials, region and the output format. You might want to configure it as the image below.

We can validate this by going to your ~/.aws/credentials

This file validates the Credentials we have just added in the terminal and displays the keys. With this step finished, we now have access to the AWS Account from our machine through AWS CLI. Great We are done with the setup…!!!

2. Create a DynamoDB Table on AWS Console and add a sample value.

Go to the AWS Console and type in DynamoDB and land on the DynamoDB Page and click on “Create Table”

Create a new table called “stocks” and add the “stock_id” as a Primary Key and go ahead and create the new table. It might take a moment to create one. We will not deep dive into Secondary Indexes and Sort Keys in this article as we are just covering the basics on the Connection.

Once the table is created, add a sample value to the table. For this article, I am adding a stock_id as “MU” with a stock_value as “65”. Since DynamoDB is a NoSQL DB, in addition to the primary key, we can add any number of values to the existing table.

Please note that the Primary Key is mandatory to add.

If you see your Table similar to the image below, then Congratulations..!!! You have created and added a sample value to your first DynamoDB Table. Way to go..!!

3. Setup the Java Spring Boot Micro Service on your local using Spring Initializr.

Let us know setup the Java Project where you create the Micro Service and connect this MicroService to the DynamoDB table which you just created.

Go to the Spring Initializr URL, where you can create the basic Spring Boot Project located at:

Just give the appropriate GroupId and the Artifact Id and add some basic dependencies to kick start your Apring Boot Application.

Once you have the Project downloaded, just modify your application.properties file to run this project on a local port and the context path

server.servlet.context-path=/dynamodb-learnings

server.port = 6060

Your Application now runs on Port 6060. I used port 6060 to keep it unique and avoid port clashes. You are free to use any port you please.

4. Integrate the DynamoDB code into your Java Application using AWS SDK and successfully read the sample value.

This is the meaty part of the Application where you write the code to connect to the DynamoDB Table on your AWS.

  1. Add the appropriate required dependencies to your pom.xml file.
  2. Create a Configuration Class and create the DynamoDB Java Bean with the appropriate Configurations.
  3. Create a Model package to create the Class which maps to the DynamoDB Table.
  4. Create a Repository Class to read the value from DynamoDB Class.
  5. Create a Controller to expose a GET HTTP Endpoint.

Add the appropriate required dependencies to your pom.xml file

Add the “aws-java-sdk-core and “aws-java-sdk-dynamodb” dependencies to you pom.xml and do an “mvn clean install” on your project to download the appropriate dependencies.

Once the dependencies are downloaded,

Create a Configuration Class and create the DynamoDB Java Bean with the appropriate Configurations.

Create a package called config and create a class called “DynamodbConfiguration class as below:

In the above code, we are creating a bean called “dynamoDBMapper” which connects to the table called “stocks” in the ‘us-east-1" region on a Standard Client Builder. This is how the DynamoDB Client is created and it reads the standard [default] values in your ./aws/credentials file and connects to the appropriate account. It further looks up for the table mentioned and then hooks itself up to the corresponding table in the account.

The above step is used to connect to DynamoDB on local. If you have Profiles mentioned in your ./aws/credentials, then you might want to use `AWSStaticCredentialsProvider` and this connects to the spcific Profile.

I will be covering how to deploy this into an EC2 Instance and to connect via an IAM role in a separate article.

3. Create a Model package to create the Class which maps to the DynamoDB Table.

Create a POJO to Serialize and Unserialize the data to and from the DynamoDB table into your code.

Add the appropriate getters and setters or use the “lombok” dependency and use the Annotation “@Data” on the top of the class to eliminate lines 10 to 24 from your code. Im explicitly going with Getters and Setters here.

Mention the HashKey and the Attribute values as applicable.

4. Create a Repository Class to read the value from DynamoDB Class.

Line 24: Import the Bean created in Step 2 into the Repository Class. The Bean is very important as it’s created only once during the Service Start up and resolves itself into the table connection and is re-used for further multiple connections.

Line 34: Expression Attributes are being built. The key to lookup here is: “stock_id”

Line 36: Expression Attribute values are being built. The value to lookup here is “MU” — which is what we have given during the table creation.

Line 40: DynamoDBQueryExpression is being built and all the parameters built above are being utilized to build the Query.

Line 41: Breaking down the condition for lookup on the table which is equivalent to `stock_id == MU’` based on the parameters supplied on Line 42 and 43.

Line 47: This is where the magic happens. We are querying the page with our conditions of lookup and the DeSerializer class — “Messages” which parses the JSON into POJO.

5. Create a Controller to expose a GET HTTP Endpoint.

We are now getting the data from DyamoDB and we need to return this data to the caller.

Let’s build a Controller class and expose a HTTP Endpoint for us to call and get the data via Curl or Postman.

Build a “Rest Controller” with a sample GET endpoint. Autowire the Repository Class and call the getDetails method and return the data to the caller.

Im keeping this GET Endpoint very simple as I have hard coded the value to lookup. Feel free to pass a Path Parameter or convert this to POST as you please. Theprimary focus of this article to talk about D configuration and a sample lookup usinf AWS SDK in Java.

Run the Server. Your Application shoud run on Port 6060 on localhost.

Making a sample Postman call should return the appropriate value which we have added in the AWS Console.

If you see this response, then Vioala…!!! You have successfully connected your MicroService to a real DynamoDB table and are able to retrieve the values.

You can find this project on github in the link below. Feel free to clone and enhance it as you please.

Bravo…!! This is a brilliant first step towards DynamoDB. Now you can explore more options to read more dynamic Values and add queries to add new values and sky is the limit for the operations. Feel free to explore more.

I hope this article of mine has shed some light on how to connect to DynamoDB from your Java Micro Service Application and read the values. Happy Coding…!!

If you have liked what you read, Please Clap hands below as many times as you can as this encourages me to write more.

--

--