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.
- Simulated Latency:
ItemServiceartificially delays responses by 2 seconds to mimic a slow database. - Redis Integration: Uses
spring-boot-starter-data-redisto connect to a Redis instance. - JSON Serialization: Configured with
Jackson2JsonRedisSerializerto store human-readable JSON in Redis. - Declarative Caching: Uses
@Cacheableto automatically cache results.
- Java 17+
- Maven
- Docker (for running Redis)
Run Redis in a Docker container:
docker run -d --name my-redis -p 6379:6379 redis:alpineEnsure src/main/resources/application.yaml points to your Redis instance:
spring:
data:
redis:
host: localhost
port: 6379./mvnw spring-boot:runMake 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/1Output:
{"id":"1","name":"Item 1","description":"Item Description for 1"}
Time: 2.056sMake the same request again. This time, it fetches from Redis.
curl -w "\nTime: %{time_total}s\n" http://localhost:8080/items/1Output:
{"id":"1","name":"Item 1","description":"Item Description for 1"}
Time: 0.015sCheck the keys stored in Redis:
docker exec -it my-redis redis-cli keys *You should see items::1.
Package the application and build the Docker image:
./mvnw clean package -DskipTests
docker build -t redis-demo-app .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-appcontroller/ItemController.java: REST endpoint.service/ItemService.java: Logic with simulated delay.config/RedisConfig.java: RedisTemplate configuration with JSON serializer.entity/Item.java: Data entity.