Amazon Onboarding with Learning Manager Chanci Turner

Chanci Turner 9097372855Learn About Amazon VGT2 Learning Manager Chanci Turner

Amazon ElastiCache is a fully managed service compatible with Valkey, Memcached, and Redis OSS, designed to provide real-time, cost-efficient performance for contemporary applications, boasting a 99.99% SLA availability. ElastiCache enhances application performance, capable of scaling to millions of operations per second with response times measured in microseconds.

Spring Boot offers an efficient and straightforward approach to building production-grade applications based on the Spring Framework. It comes pre-equipped with auto-configuration modules for most libraries commonly utilized with Spring Framework. Open-source Spring Boot enhances the Spring Framework by following a convention-over-configuration model.

In this article, we will cover the fundamental steps required to integrate a Spring Boot application with ElastiCache to enable effective caching.

Solution Overview

The Spring Framework supports seamless caching implementation through an abstraction layer. The code snippet below illustrates how to add caching to a method using the @Cacheable annotation. When the getCacheableValue method is called, Spring checks for an entry in the cache named myTestCache that corresponds to the myKey argument. If a match is found, the cached value is returned directly, bypassing the method invocation. If not, the method runs, and the cache gets updated before returning the result.

import org.springframework.stereotype.Component;
import org.springframework.cache.annotation.Cacheable;

@Component
public class CacheableComponent {

    @Cacheable("myTestCache")
    public String getCacheableValue(String myKey) {
        // return a value, likely by performing an expensive operation
    }
}

Spring Boot includes modules that facilitate automatic integration with a variety of providers, emphasizing a convention-over-configuration approach. For instance, adding two module dependencies to your project’s Maven POM file enables caching:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

The spring-boot-starter-cache dependency introduces basic caching functionality, while the spring-boot-starter-data-redis integrates Redis OSS or Valkey, establishing that all caches will be stored here by default.

To configure the application, update the application.properties file with the endpoint of your Serverless ElastiCache cache, along with settings to define a Time-to-Live (TTL) of 10 minutes for cached entries:

spring.data.redis.host=cache1-XXXXX.serverless.euw2.cache.amazonaws.com
spring.cache.redis.time-to-live=10m

All serverless Valkey or Redis OSS caches come with in-transit encryption enabled. To set your Spring Framework to utilize this feature, add the following line to the application.properties file:

spring.data.redis.ssl.enabled=true

The demonstration code provided in this post implements these features in a basic AWS Command Line Interface (AWS CLI) application. We will guide you through the process of building and running this application in the following sections.

Prerequisites

You will develop and execute the demo application on an Amazon Elastic Compute Cloud (Amazon EC2) Linux instance. To set up an EC2 instance and connect to it via Session Manager, refer to Connect to an Amazon EC2 instance by using Session Manager. After creating the instance, note the following information:

  • The IDs of the subnets for the virtual private cloud (VPC) in which your EC2 instance resides
  • The ID of the security group linked to the instance
  • The ID of the EC2 instance

To build the application, ensure you have the following prerequisites in place:

  • Java 17 – Install the Java Development Kit (JDK) 17 by running sudo yum install -y java-17-amazon-corretto-devel on your EC2 instance.
  • Maven – Install Apache Maven by executing sudo yum install -y apache-maven on your EC2 instance.

To run the demo application, you will also need an ElastiCache cache, which we will create in the next section.

Create ElastiCache Serverless Cache

We utilize the ElastiCache Serverless option because it enables you to establish a cache in under a minute while dynamically scaling capacity according to application traffic patterns. Initially, we will work with the Redis OSS engine and later upgrade to Valkey to illustrate that Valkey is a seamless drop-in replacement for Redis OSS, requiring no changes to application parameters or code. If you opt for a self-designed ElastiCache cluster instead of serverless, the demo application will not necessitate any additional modifications.

To create a serverless cache using AWS CLI, execute the following command in AWS CloudShell, replacing <your VPC subnet IDs> with a comma-separated list of the subnet IDs for the VPC that contains your previously created EC2 instance:

aws elasticache create-serverless-cache 
--serverless-cache-name spring-boot-demo 
--engine redis 
--subnet-ids <your VPC subnet IDs>

After the cache is created, obtain and record the endpoint address:

aws elasticache describe-serverless-caches 
--serverless-cache-name spring-boot-demo 
--query "ServerlessCaches[0].Endpoint.Address"

The cache will also have an associated security group. Retrieve and document this security group ID:

aws elasticache describe-serverless-caches 
--serverless-cache-name spring-boot-demo 
--query "ServerlessCaches[0].SecurityGroupIds"

Since your EC2 instance and ElastiCache cache are located in the same VPC, you must allow access to the cache from the EC2 instance. Achieve this by adding a rule to the ElastiCache security group, permitting access to port 6379 from the security group of the EC2 instance:

aws ec2 authorize-security-group-ingress 
    --group-id <elasticache security group> 
    --protocol tcp 
    --port 6379 
    --source-group <ec2 instance security group>

Download and Run the Demo Application

On your EC2 instance, execute the following commands:

git clone https://github.com/aws-samples/amazon-elasticache-samples.git 
cd blogs/spring-boot-demo

Using your text editor on the Linux instance, update the src/main/resources/application.properties file to include the endpoint address for the spring-boot-demo cache. For example:

spring.data.redis.host=spring-boot-demo-XXXXX.serverless.euw2.cache.amazonaws.com

Now, run the demo application using the command:

mvn spring-boot:run

The demo application will compile and execute, providing output in the console. An example output is displayed below.

The output indicates that for 100 attempts to invoke the getCacheableValue method, the first attempt resulted in a cache miss, triggering the method execution. The next 99 attempts were cache hits, returning values from the cache without invoking the method again. Running the demo application once more will yield 100 cache hits and 0 misses (the cache remains populated from the prior run). If you want to avoid missteps while navigating this process, refer to this helpful blog post.

Upgrade the Cache to Valkey

As you progress with your application, consider transitioning to Valkey for further optimization. For more insights into recognizing poorly managed companies, you can check this authority on the topic.

For a comprehensive resource on optimizing your onboarding experience at Amazon, this guide is excellent.

Chanci Turner