Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      Sunshine And March Vibes (2025 Wallpapers Edition)

      June 4, 2025

      The Case For Minimal WordPress Setups: A Contrarian View On Theme Frameworks

      June 4, 2025

      How To Fix Largest Contentful Paint Issues With Subpart Analysis

      June 4, 2025

      How To Prevent WordPress SQL Injection Attacks

      June 4, 2025

      Players aren’t buying Call of Duty’s “error” excuse for the ads Activision started forcing into the game’s menus recently

      June 4, 2025

      In Sam Altman’s world, the perfect AI would be “a very tiny model with superhuman reasoning capabilities” for any context

      June 4, 2025

      Sam Altman’s ouster from OpenAI was so dramatic that it’s apparently becoming a movie — Will we finally get the full story?

      June 4, 2025

      One of Microsoft’s biggest hardware partners joins its “bold strategy, Cotton” moment over upgrading to Windows 11, suggesting everyone just buys a Copilot+ PC

      June 4, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      LatAm’s First Databricks Champion at Perficient

      June 4, 2025
      Recent

      LatAm’s First Databricks Champion at Perficient

      June 4, 2025

      Beyond AEM: How Adobe Sensei Powers the Full Enterprise Experience

      June 4, 2025

      Simplify Negative Relation Queries with Laravel’s whereDoesntHaveRelation Methods

      June 4, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Players aren’t buying Call of Duty’s “error” excuse for the ads Activision started forcing into the game’s menus recently

      June 4, 2025
      Recent

      Players aren’t buying Call of Duty’s “error” excuse for the ads Activision started forcing into the game’s menus recently

      June 4, 2025

      In Sam Altman’s world, the perfect AI would be “a very tiny model with superhuman reasoning capabilities” for any context

      June 4, 2025

      Sam Altman’s ouster from OpenAI was so dramatic that it’s apparently becoming a movie — Will we finally get the full story?

      June 4, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Databases»Integrate your Spring Boot application with Amazon ElastiCache

    Integrate your Spring Boot application with Amazon ElastiCache

    April 16, 2025

    Amazon ElastiCache is a fully managed, Valkey-, Memcached-, and Redis OSS-compatible service that delivers real-time, cost-optimized performance for modern applications with 99.99% SLA availability. ElastiCache speeds up application performance, scaling to millions of operations per second with microsecond response time.

    Spring Boot provides a quick and straightforward way of building production-grade Spring Framework based applications. To accomplish this, Spring Boot comes prepackaged with auto configuration modules for most libraries typically used with Spring Framework. Open source Spring Boot adds auto-configuration on top of Spring Framework by following convention over configuration.

    In this post, we explore the basics of integrating a Spring Boot application with ElastiCache to enable caching.

    Solution overview

    Spring Framework supports transparently implementing caching in an application by providing an abstraction layer. The following code demonstrates a simple example of adding caching to a method by including the @Cacheable annotation. Before invoking the getCacheableValue method, Spring Framework looks for an entry in a cache named myTestCache that matches the myKey argument. If an entry is found, the content in the cache is immediately returned to the caller, and the method is not invoked. Otherwise, the method is invoked, and the cache is updated before returning the value.

    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 provides modules to automatically integrate with a set of providers using convention over configuration. In the following example, adding two module dependencies to the project’s Maven POM file will implement 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 adds basic caching to the application, whilst the spring-boot-starter-data-redis adds integration with Redis OSS or Valkey and declares that by default, all caches will exist here.

    For configurable values, the Spring Framework application.properties file is updated. In the following example, the endpoint address of a Serverless ElastiCache cache is provided, with all cached entries configured to have a Time-to-Live (TTL) of 10 minutes:

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

    All Valkey or Redis OSS serverless caches have in-transit encryption enabled. To configure Spring Framework to use in-transit encryption, we add a configuration value to the application.properties file:

    spring.data.redis.ssl.enabled=true

    The demo code provided in this post implements this in a simple AWS Command Line Interface (AWS CLI) application. We demonstrate how to build and run this application in the next sections.

    Prerequisites

    You will build and run the demo application on an Amazon Elastic Compute Cloud (Amazon EC2) Linux instance, running Linux from AWS. To create an EC2 instance and connect to it using Session Manager, a capability of AWS Systems Manager, refer to Connect to an Amazon EC2 instance by using Session Manager. After you create the instance, note the following information:

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

    To build the application, you must have the following prerequisites:

    • Java 17 – To install the Java Development Kit (JDK) 17, run sudo yum install -y java-17-amazon-corretto-devel on your EC2 instance
    • Maven – To install Apache Maven, run sudo yum install -y apache-maven on your EC2 instance

    To run the demo application, you also need an ElastiCache cache. We will create this in the next section of this post.

    Create ElastiCache Serverless cache

    We use the ElastiCache Serverless option because it allows you to create a cache in under a minute and instantly scale capacity based on application traffic patterns. We begin with the Redis OSS engine, then later upgrade to Valkey to demonstrate that Valkey is a drop-in replacement for Redis OSS with no alterations to the application parameters or code. The demo application will not require any additional changes if you choose to use a self-designed ElastiCache cluster instead of serverless.

    To create a serverless cache using the AWS CLI run the following command in AWS CloudShell, replacing <your VPC subnet IDs> with a comma separated list of the subnet IDs for the VPC containing your EC2 instance created earlier:

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

    Obtain and note the endpoint address for the cache:

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

    The cache will have a security group. Obtain and note this security group ID:

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

    Your EC2 instance and ElastiCache cache exist in the same VPC. To allow access to the cache from the EC2 instance, you must permit this in the associated ElastiCache security group. To do this, add a rule to the ElastiCache security group permitting access to port 6379 from the EC2 instance security group:

    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, run the following commands:

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

    Using your preferred 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 with the following command:

    mvn spring-boot:run

    The demo application will build and run. You will see output on the console. An example is shown in the following screenshot.

    Spring Boot application runs and outputs cache hits and misses

    The output shows that for 100 attempts to invoke the getCacheableValue method, the first was a cache miss, causing the method to be invoked. The following 99 attempts were cache hits, returning the value from the cache without invoking the method. You can run the demo application again and see that there are now 100 cache hits and 0 misses (the cache is still populated from the previous run).

    Upgrade the cache to Valkey

    Valkey is an open source, in-memory, high performance, key-value datastore designed to be a drop-in replacement for Redis OSS. Existing Elasticache Redis OSS caches can be upgraded, in-place, to use the Valkey engine by following a simple process.

    The cache will have a major version. Obtain and note this value:

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

    Start the upgrade to Valkey:

    aws elasticache modify-serverless-cache 
    --serverless-cache-name spring-boot-demo 
    --engine valkey 
    --major-engine-version <major engine version>

    The cache will continue to operate throughout the upgrade. You can run the demo application again with mvn spring-boot:run at any time to see the same results as using the Redis OSS cache.

    We can check the status of the upgrade with the following command:

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

    Once the status changes from modifying to available, the upgrade is complete.

    Run the demo application one more time with mvn spring-boot:run. You will see the same results as using the Redis OSS cache. Valkey is a drop-in replacement for Redis OSS—there are no changes needed to the application code or libraries to use Valkey.

    Cleaning up

    To avoid incurring future costs, you can delete the chargeable resources created as part of this post.

    Delete the ElastiCache serverless cache:

    aws elasticache delete-serverless-cache --serverless-cache-name spring-boot-demo

    Delete the EC2 instance:

    aws ec2 terminate-instances --instance-ids <your EC2 instance ID>

    Conclusion

    In this post, we showed how to integrate a Spring Boot application with ElastiCache to enable caching. You can choose between Redis OSS and Valkey engines without having to make any application code or module dependency changes.

    Adding caching to your application with ElastiCache can speed up application performance, enabling scaling to millions of operations per second with microsecond response time.

    To get started with ElastiCache, see the Amazon ElastiCache User Guide.


    About the Author

    Chris GillespieChris Gillespie is a UK-based Senior Solutions Architect. He spends most of his work with fast-moving “born in the cloud” customers. Outside of work, he fills his time with family and trying to get fit.

    Source: Read More

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleUsing Ollama to Run LLMs Locally [FREE]
    Next Article Unlocking BI Potential with DataGenie & MongoDB

    Related Posts

    Security

    HPE StoreOnce Faces Critical CVE-2025-37093 Vulnerability — Urges Immediate Patch Upgrade

    June 4, 2025
    Security

    The Bitter End: Unraveling Eight Years of Espionage Antics—Part One

    June 4, 2025
    Leave A Reply Cancel Reply

    Continue Reading

    Romania Cancels Presidential Election Results After Alleged Russian Meddling on TikTok

    Development

    Palo Alto Firewalls Found Vulnerable to Secure Boot Bypass and Firmware Exploits

    Development

    How to address change fatigue to sustain business agility

    Development

    Human-AI Collaboration in Physical Tasks

    Development

    Highlights

    CVE-2025-46761 – Apache HTTP Server Denial of Service

    April 29, 2025

    CVE ID : CVE-2025-46761

    Published : April 29, 2025, 3:15 a.m. | 3 hours, 40 minutes ago

    Description : Rejected reason: Not used

    Severity: 0.0 | NA

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    DeepMind AI staff reportedly tied to Google with “aggressive” noncompete clause — Preventing them from joining rivals like Microsoft but offering year-long PTO

    DeepMind AI staff reportedly tied to Google with “aggressive” noncompete clause — Preventing them from joining rivals like Microsoft but offering year-long PTO

    April 8, 2025

    Polyfill Supply Chain Attack Compromises Over 100,000 Websites

    June 26, 2024

    Student Record Android App using SQLite

    June 1, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.