Home

How to Boost Spring Boot Performance by 100x using Redis Cache

In this tutorial, we will take a "Slow API" (that takes 3 seconds to load) and turn it into a "Fast API" (that loads in milliseconds) using Redis Caching.

Tutorial Description

We will simulate a product database. When a user asks for product details, it simulates a slow database query. We will then implement Redis to store this result in memory so that subsequent requests are instant.

Tools and Technologies

  • Java 21
  • Spring Boot 3.5.x
  • Redis (The most popular in-memory data store)
  • Docker (To run Redis)

Development Steps

  • Step 1: Run Redis using Docker
  • Step 2: Add Dependencies
  • Step 3: Configure Redis and Enable Caching
  • Step 4: Create the Service (The "Slow" Logic)
  • How to Test This? (The "Wow" Factor)

1. Step 1: Run Redis using Docker

Instead of installing Redis manually, we use Docker. Create a docker-compose.yml file.

1. File: docker-compose.yml

Run docker: docker-compose up -d
Code Example

2. Step 2: Add Dependencies (File: build.gradle)

We need the Spring Data Redis starter.

Code Example

2. Step 3: Configure Redis and Enable Caching

We need to tell Spring Boot where Redis is running and explicitly turn on the caching feature using @EnableCaching.

1. File: src/main/resources/application.properties

 

Code Example

2. File: src/main/java/com/planetlearning/cache/CacheApplication.java

Code Example

3. Step 4: Create the Service (The "Slow" Logic)

We will create a service that simulates a slow database call using Thread.sleep(). We use the @Cacheable annotation to fix it.

1. File: src/main/java/com/planetlearning/cache/service/ProductService.java

Code Example

4. Step 5: The Controller

Expose the endpoints to test the speed.

1. File: src/main/java/com/planetlearning/cache/controller/ProductController.java

Code Example

5. How to Test This? (The "Wow" Factor)

  1. First Request (The Slow One):
    • Call GET http://localhost:8080/api/products/1
    • Result: You will wait 3 seconds. The console will print: "Going to sleep..."
    • Why? The cache was empty, so it ran the code.
  2. Second Request (The Fast One):
    • Call GET http://localhost:8080/api/products/1 again.
    • Result: It returns Instantly (2ms). The console prints NOTHING.
    • Why? Spring Boot fetched the result directly from Redis and skipped the Java code entirely.
  3. Update Data (Cache Eviction):
    • Call PUT http://localhost:8080/api/products/1?price=1000
    • Why? This triggers @CacheEvict, which deletes the old data from Redis so the user doesn't see old prices.

Why learn this?

In a real job, if a page is loading slowly, your boss will ask you to fix it. This tutorial teaches you exactly how to solve that problem in 10 minutes.