This project demonstrates the use of a multi-layer cache with Caffeine and Redis in a Spring Boot application. Full explanation available here: https://gaetanopiazzolla.github.io/java/2025/01/27/multicache.html
The application uses a custom cache manager to manage two levels of caching:
- Caffeine Cache: First-level cache for fast, in-memory access.
- Redis Cache: Second-level cache for distributed caching.
The following Mermaid diagram illustrates the process of getting, putting, and evicting data from the caches:
sequenceDiagram
participant Client
participant DataService
participant CustomCache
participant CaffeineCache
participant RedisCache
Client->>DataService: getData(id)
DataService->>CustomCache: get(id)
CustomCache->>CaffeineCache: get(id)
alt CaffeineCache hit
CaffeineCache-->>CustomCache: return value
else CaffeineCache miss
CaffeineCache-->>CustomCache: return null
CustomCache->>RedisCache: get(id)
alt RedisCache hit
RedisCache-->>CustomCache: return value
CustomCache->>CaffeineCache: put(id, value)
else RedisCache miss
RedisCache-->>CustomCache: return null
CustomCache-->>DataService: return null
end
end
CustomCache-->>DataService: return value
DataService-->>Client: return value
Client->>DataService: insertData(id, newData)
DataService->>CustomCache: put(id, newData)
CustomCache->>CaffeineCache: put(id, newData)
CustomCache->>RedisCache: put(id, newData)
Client->>DataService: evictData(id)
DataService->>CustomCache: evict(id)
CustomCache->>CaffeineCache: evict(id)
CustomCache->>RedisCache: evict(id)
DataService: Service class with methods to get, insert, and evict data.CustomCacheManager: Custom cache manager to manage Caffeine and Redis caches.CustomCache: Custom cache implementation that combines Caffeine and Redis caches.
The integration tests verify the behavior of the multi-layer cache. To run the tests, use the following command:
./gradlew testThis project is licensed under the MIT License.