Skip to content

GaetanoPiazzolla/spring-boot-multi-layer-cache

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Multi-Layer Cache Application

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

Overview

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.

Cache Operations

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)
Loading

Project Structure

  • 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.

Running the Tests

The integration tests verify the behavior of the multi-layer cache. To run the tests, use the following command:

./gradlew test

License

This project is licensed under the MIT License.

About

Implementing Caffeine L1 and Redis L2 caching with a nice Abstraction

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published