javaspring-bootredisspring-data-redisdistributed-caching

What is the default cache strategy when using Redis with spring or spring boot?


There are various cache strategies like: Cache Aside, Read Through, Write Through, Write Behind, Write Around.

When Redis is used with spring boot using spring-boot-starter-data-redis dependency, what is the default Cache Strategy. And how can this be changed. Any reference will be greatly appreciated.


Solution

  • By default, you get cache aside, our cache usage in the Spring boot app looks something similar to this

    @Cacheable(cacheNames = "someCache")
    public String cacheThis(String id){
        return "this Is it";
    }
    

    In most of the scenarios in the spring boot app, we cache the result of JPA or other DB queries. In such cases, we add Cacheable on the query method, which gives us cache aside feature.

    An application can emulate the functionality of read-through caching by implementing the cache-aside strategy. This strategy loads data into the cache on demand.

    Cache Aside

    Ref: https://learn.microsoft.com/en-us/azure/architecture/patterns/cache-aside

    Using cache aside pattern is not the always solution to a problem, depending on your use case you might have to change the caching strategy. Changing caching strategy is not straight forward except some annotations we know from the Spring framework like

    You need to update your application code to use other caching strategies, though you can build any caching strategy using these annotations. If you don't like to use these annotations then play with the actual cache object, at any time you can call Cache methods to modify the cache.

    eg

    Cache myCache = cacheManager.getCache("myCache"); 
    

    Once you have a cache object, you can call all relevant methods, some methods may not work as expected due to the limitation of the underlying cache.