Search code examples
springspring-bootspring-cache

Spring cache @Cacheable and @CachePut. If exception is thrown inside method of @cachePut, get data from Cache


I have a spring cache requirement:

I need to request to a server to get some data and store the results in spring cache. The same request can give me different results every time so I decided to use @cachePut so that every time I can go inside my function and cache gets updated.

@CachePut(value="mycache", key="#url")
public String getData(String url){
    try{
        // get the data from server
        // update the cache
        // return data
    } catch(){
        // return data from cache
    }   
}

Now there is a twist. If the server is down and I am not able to get the response; I want my data from the cache (stored in previous requests).

If i use @Cacheable, I can't get the updated data. What is the clean way to do this? Something like catching an exception and return the data from cache.


Solution

  • you can get the cache implementation like this and handle the cache.

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.Cache;
    import org.springframework.cache.CacheManager;
    import org.springframework.cache.annotation.CacheConfig;
    import org.springframework.cache.annotation.CachePut;
    import org.springframework.stereotype.Service;
    
    @Service
    @CacheConfig(cacheNames="mycache") // refer to cache/ehcache-xxxx.xml 
    public class CacheService {
        @Autowired private CacheManager manager;
        @CachePut(key="#url")
        public String getData(String url) {
            try {
                //do something.
                return null;
            }catch(Exception e) {
                Cache cache = manager.getCache("mycache");
                return (String) cache.get(url).get();
            }
        }
    }