Skip to content

devraselmahmud/redis-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spring Boot Redis Caching Demo

This project demonstrates how to integrate Redis Caching into a Spring Boot application to drastically improve performance. It simulates a slow service and shows how caching can turn a 2-second response into an instant one.

🚀 Features

  • Simulated Latency: ItemService artificially delays responses by 2 seconds to mimic a slow database.
  • Redis Integration: Uses spring-boot-starter-data-redis to connect to a Redis instance.
  • JSON Serialization: Configured with Jackson2JsonRedisSerializer to store human-readable JSON in Redis.
  • Declarative Caching: Uses @Cacheable to automatically cache results.

🛠️ Prerequisites

  • Java 17+
  • Maven
  • Docker (for running Redis)

🏃‍♂️ Getting Started

1. Start Redis

Run Redis in a Docker container:

docker run -d --name my-redis -p 6379:6379 redis:alpine

2. Configure Application

Ensure src/main/resources/application.yaml points to your Redis instance:

spring:
  data:
    redis:
      host: localhost
      port: 6379

3. Run the Application

./mvnw spring-boot:run

🧪 How to Test

Step 1: The "Slow" Request (Cache Miss)

Make a request to the API. Since the cache is empty, it will hit the "database" (service) and take 2 seconds.

curl -w "\nTime: %{time_total}s\n" http://localhost:8080/items/1

Output:

{"id":"1","name":"Item 1","description":"Item Description for 1"}
Time: 2.056s

Step 2: The "Fast" Request (Cache Hit)

Make the same request again. This time, it fetches from Redis.

curl -w "\nTime: %{time_total}s\n" http://localhost:8080/items/1

Output:

{"id":"1","name":"Item 1","description":"Item Description for 1"}
Time: 0.015s

Step 3: Verify in Redis

Check the keys stored in Redis:

docker exec -it my-redis redis-cli keys *

You should see items::1.

🐳 Docker Support

1. Build the Application

Package the application and build the Docker image:

./mvnw clean package -DskipTests
docker build -t redis-demo-app .

2. Run with Docker

Run the container, linking it to your Redis instance and setting the host variable:

docker run -d -p 8080:8080 \
  --link my-redis:redis-alias \
  -e REDIS_HOST=redis-alias \
  redis-demo-app

📂 Project Structure

  • controller/ItemController.java: REST endpoint.
  • service/ItemService.java: Logic with simulated delay.
  • config/RedisConfig.java: RedisTemplate configuration with JSON serializer.
  • entity/Item.java: Data entity.

About

Spring Boot Redis Caching Demo

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published