A complete, production-ready guide to implementing Redis caching in a Spring Boot 3 API to improve performance of frequently accessed database records.
This example demonstrates a clean approach to implementing Redis caching using Spring Boot 3 and Spring Data Redis. We use Spring's Cache Abstraction (`@Cacheable`, `@CacheEvict`, `@CachePut`) to minimize boilerplate code.
The Flow: When a GET request is made, the application first checks the Redis cache. If the data exists (Cache Hit), it is returned immediately. If not (Cache Miss), the data is fetched from the MySQL database, saved to Redis, and then returned. Subsequent requests will be served from the cache until the data is updated or deleted, which triggers a cache eviction.
Add the required dependencies for Spring Web, Data Redis, Data JPA, MySQL, and Lombok.
Configure your MySQL database connection, enable Redis caching, and set the Redis host and port.
Note: Make sure you have a Redis server running locally on port 6379. You can use Docker: `docker run --name redis -p 6379:6379 -d redis`.
We define a `Product` entity. Note that the entity must implement `Serializable` for it to be cached in Redis.
We configure the `RedisCacheManager` to serialize values as JSON (making them human-readable in Redis) and set a Default Time-To-Live (TTL). Don't forget `@EnableCaching` on this config or the main application class.
This is where the magic happens. We use `@Cacheable` to cache read operations, and `@CacheEvict` or `@CachePut` for write/update operations.
The controller exposes REST endpoints and delegates to the caching service.
With the application running, let's observe the behavior of the cache hits versus database hits.
By caching frequent read requests (like getting a product by ID), we bypassed the MySQL database and network latency entirely.
In the example logs above, the response time drops from ~150ms (fetching from DB and saving to Redis) to ~5ms (fetching directly from Redis). This drastically reduces database load and speeds up the API response.