DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • Spring2quarkus — Spring Boot to Quarkus Migration
  • iOS Spring Boot Code Generation in One Minute With Clowiz
  • Develop a Secure CRUD Application Using Angular and Spring Boot

Trending

  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • How to Practice TDD With Kotlin
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  1. DZone
  2. Data Engineering
  3. Databases
  4. How to Build a Chat App With Spring Boot and DynamoDB

How to Build a Chat App With Spring Boot and DynamoDB

By 
Bogdan Nechyporenko user avatar
Bogdan Nechyporenko
DZone Core CORE ·
Nov. 13, 20 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
6.9K Views

Join the DZone community and get the full member experience.

Join For Free

The goal of this article is to show the simplest chat implementation with one server and multiple clients based on Spring Boot and deployed to AWS.

For source code, you can refer to this link: https://github.com/acierto/aws-chat.git

First I'd like to tell amount the used API in the project:

  1.  User first has to connect to the server with api GET call /connect?name=USER_NAME. If your username is unique and you successfully connected, you'll get back a token. You will need this token to send messages or be able disconnect. 
  2. To send a message, you need to send a POST call /send?token=TOKEN, and in the body of the api call, enclose the message text. If the message is sent successfully, as a result you'll get SENT in response. 
  3. You can check the entire history of all users by GET api call /history 
  4. And when you would like to disconnect by sending GET api call /disconnect .

It's a very simple API and could be greatly improved, but the goal is not implementing a perfect API for chat, or handling all potential cases. Rather we'll see how to combine the things together. And keep the less code to easier grasp for beginners how it works.

Before going into details of the implementation, I'd suggest you to run that application locally, to configure so that you can experiment with what you read later.

First, you need to configure the AWS CLI at your computer. You can follow AWS documentation for that.

The most important that you have created ~/.aws/credentials having there something like:

Plain Text
xxxxxxxxxx
1
 
1
[default]
2
aws_access_key_id=...
3
aws_secret_access_key=...


and ~/.aws/config to specify your region 

Plain Text
xxxxxxxxxx
1
 
1
[default]
2
region=eu-west-1
3
output=json


After that you need to:

  • Checkout the project: git clone git@github.com:acierto/aws-chat.git
  • cd aws-chat && ./gradlew :aws-chat-server:bootRun - this command starts the server. First time it can take a while to pull the docker image of Dynamodb. Wait till it starts.
  • Then in a separate terminal window you can start a client (or multiple clients): cd aws-chat && ./gradlew :aws-chat-client:bootRun . 

Now let's see what is happening under the hood of the server part. The main class which boots the application is ChatServerApplication. You can see the annotation on that class @SpringBootAnnotation. This annotation does many things if you have a look of its sources

Java
xxxxxxxxxx
1
 
1
@Target(ElementType.TYPE)
2
@Retention(RetentionPolicy.RUNTIME)
3
@Documented
4
@Inherited
5
@SpringBootConfiguration
6
@EnableAutoConfiguration
7
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
8
      @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })


It runs auto-configuration of multiple modules and scans all packages. You can tweak it, by disabling some configurations or restricting which packages to scan. In this example it is not requires though.

Alone with boosting the application, we also setting up and running AWS Dynamo DB locally. So it's easy and free to work with it. The entire configuration for this part is done in build.gradle:

Groovy
xxxxxxxxxx
1
24
 
1
repositories {
2
    mavenCentral()
3
    maven {
4
        url 'http://dynamodb-local.s3-website-us-west-2.amazonaws.com/release'
5
    }
6
}
7
8
configurations {
9
    dynamodb
10
}
11
12
dependencies {
13
    implementation 'com.amazonaws:aws-java-sdk-core:1.11.880'
14
    implementation 'com.amazonaws:aws-java-sdk-dynamodb:1.11.880'
15
    implementation 'com.github.derjust:spring-data-dynamodb:5.1.0'
16
    implementation 'com.amazonaws:DynamoDBLocal:1.13.2'
17
18
    dynamodb fileTree(dir: 'lib', include: ["*.dylib", "*.so", "*.dll"])
19
    dynamodb 'com.amazonaws:DynamoDBLocal:1.13.2'
20
}
21
22
dockerCompose {
23
    useComposeFiles = ['docker-compose.yml']
24
}


And docker-compose.yml with docker image of DynamoDB

YAML
xxxxxxxxxx
1
 
1
version: '3.7'
2
services:
3
  dynamodb-local:
4
    image: amazon/dynamodb-local:latest
5
    container_name: dynamodb-local
6
    ports:
7
      - "8000:8000"


It's very nice to be able to browse the data and you can configure it with next steps:

  • npm install -g dynamodb-admin
  • export DYNAMO_ENDPOINT=http://localhost:8000
  • dynamodb-admin

Once you finish with that you can see something like this:

live application

It also allows to manipulate with data, so really handy to make it up and running.

The configuration to the database is configured in application.yml, you can configure there the endpoint:

YAML
xxxxxxxxxx
1
 
1
aws:
2
  server:
3
    dynamodb:
4
      endpoint:
5
        http://localhost:8000


Configuration in Java is pretty simple for that. You can find many examples where also specified AWS credentials here, but it is not needed and actually an anti-pattern, as you will have to keep those credentials in your configuration files. Better to have them only in ~/.aws/credentials and make application read it implicitly:

Java
xxxxxxxxxx
1
17
 
1
@Configuration
2
@EnableDynamoDBRepositories(basePackages = "com.acierto.awschat.server.storage.repositories")
3
public class DynamoDBConfig {
4
5
    @Value("${aws.server.dynamodb.endpoint}")
6
    private String dynamoDbEndpoint;
7
8
    @Value("${aws.server.signingRegion}")
9
    private String signingRegion;
10
11
    @Bean
12
    public AmazonDynamoDB amazonDynamoDB() {
13
        return AmazonDynamoDBClientBuilder.standard()
14
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(dynamoDbEndpoint, signingRegion))
15
                .build();
16
    }
17
}


To make the work with DynamoDb easy and minimum from the code perspective, here configured Spring-Data. It really simplifies a lot of internal things which you have to know to work with this database. I recommend to use it as well. 

When application boots the first time, 2 tables are created:

Java
xxxxxxxxxx
1
27
 
1
public class StorageManager {
2
3
    private final AmazonDynamoDB amazonDynamoDB;
4
5
    public StorageManager(AmazonDynamoDB amazonDynamoDB) {
6
        this.amazonDynamoDB = amazonDynamoDB;
7
    }
8
9
    public void createTables() {
10
        createTable(Message.class);
11
        createTable(User.class);
12
    }
13
14
    private boolean tableExists(Class<?> table) {
15
        ListTablesResult result = amazonDynamoDB.listTables();
16
        return result.getTableNames().contains(table.getSimpleName());
17
    }
18
19
    private void createTable(Class<?> table) {
20
        if(!tableExists(table)) {
21
            DynamoDBMapper dynamoDBMapper = new DynamoDBMapper(amazonDynamoDB);
22
            CreateTableRequest tableRequest = dynamoDBMapper.generateCreateTableRequest(table);
23
            tableRequest.setProvisionedThroughput(new ProvisionedThroughput(1L, 1L));
24
            amazonDynamoDB.createTable(tableRequest);
25
        }
26
    }
27
}


There is no built in functionality in DynamoDB to create table only when it doesn't exist, and no API to check it just by name, so one of the solutions as here, to list all created tabes so far and check there.

When you create table in DynamoDB you have to specify the throughput new ProvisionedThroughput(1L, 1L)  , it's important as the bigger throughput you specify the higher pay check you'll get in the end of the month. In real application you have to tune it, so that it's optimal for users and your bill. First parameter is responsible for read throughput and second for write. The capacity is measure in Units. I advice to check official link to read about that https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html as there quite some theory how to calculate it. And if you are going to take AWS Developer Certification exam, you have to know it well.

Querying with dynamodb-spring-data is very simple, you have to only define interfaces:

Java
xxxxxxxxxx
1
 
1
@EnableScan
2
public interface UserRepository extends CrudRepository<User, String> {
3
    Optional<User> findById(String id);
4
5
    User findByName(String name);
6
7
    User findBySessionToken(String sessionToken);
8
9
}
Java
xxxxxxxxxx
1
 
1
@EnableScan
2
public interface MessageRepository extends CrudRepository<Message, String> {
3
    Optional<Message> findById(String id);
4
}


All queries will be built for you.

One thing what is only required from you, to properly define entities for the database. Like let's have a look at user:

Java
xxxxxxxxxx
1
11
 
1
@DynamoDBTable(tableName = "User")
2
public class User {
3
    @DynamoDBHashKey
4
    @DynamoDBAutoGeneratedKey
5
    private String id;
6
7
    @DynamoDBAttribute
8
    private String name;
9
10
    @DynamoDBAttribute
11
    private String sessionToken;


Only one field is mandatory for DynamoDb, is to define a hash key.

With a massive data you have to have a look at the usage of DynamoDBIndexHashKey and DynamoDBIndexRangeKey. The difference between them only what kind of cache to use - global or local. As you might guess from names it depends where is the data is located, across different partitions or on the same partition. Though each of the option has own limitations which have to be considered carefully.

The client is pretty simple, it is also a spring-boot application which sends 3 messages and signs off. In resources there are 2 files added with the list of names and messages, which are picked randomly. If you will start playing with a big load of clients, could happen a name collision, but it's fine and user process will not be able to send messages.

In logs you will see similar to this:

Plain Text
xxxxxxxxxx
1
 
1
2020-11-03 21:45:00.318  INFO 26710 --- [           main] c.a.a.client.ChatClientApplication       : Started ChatClientApplication in 1.252 seconds (JVM running for 1.59)
2
2020-11-03 21:45:00.399  INFO 26710 --- [poolScheduler-1] c.a.a.client.ScheduledMessageSender      : [200 OK] Received response 977afd97-a2d5-41ec-8e75-0310281de75f
3
2020-11-03 21:45:00.469  INFO 26710 --- [poolScheduler-1] c.a.a.client.ScheduledMessageSender      : [200 OK] Received response SENT
4
2020-11-03 21:45:01.411  INFO 26710 --- [poolScheduler-1] c.a.a.client.ScheduledMessageSender      : [200 OK] Received response SENT
5
2020-11-03 21:45:02.424  INFO 26710 --- [poolScheduler-1] c.a.a.client.ScheduledMessageSender      : [200 OK] Received response SENT
6
2020-11-03 21:45:03.403  INFO 26710 --- [poolScheduler-1] c.a.a.client.ScheduledMessageSender      : [200 OK] Received response SENT
7
2020-11-03 21:45:04.720  INFO 26710 --- [poolScheduler-1] c.a.a.client.ScheduledMessageSender      : [200 OK] Received response SIGNED OFF
8
2020-11-03 21:45:04.742  INFO 26710 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
9
2020-11-03 21:45:04.742  INFO 26710 --- [extShutdownHook] heduledMessageSender$CustomTaskScheduler : Shutting down ExecutorService 'poolScheduler'


The scheduler is running to send a message each second and after some interval it is stopped, user is disconnecting and the entire process is killing by System.exit(0).

I also prepared a docker file to run it on EC2 

Dockerfile
xxxxxxxxxx
1
 
1
FROM openjdk:11-jdk-alpine
2
ARG JAR_FILE=target/*.jar
3
COPY ${JAR_FILE} aws-chat-server.jar
4
ENTRYPOINT ["java","-jar","/aws-chat-server.jar"]


You can also experiment with that by running multiple instances of clients on ECS, to make a load, changing the frequency and the amount of send messages, etc. Take into account that you will have to configure Dynamo DB on your AWS account first. But it will be quite easy by following GUI wizard.

Spring Framework Spring Boot Database application app Plain text AWS

Opinions expressed by DZone contributors are their own.

Related

  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • Spring2quarkus — Spring Boot to Quarkus Migration
  • iOS Spring Boot Code Generation in One Minute With Clowiz
  • Develop a Secure CRUD Application Using Angular and Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!