Spring 缓存@Cacheable 和@CachePut。如果在@cachePut 方法内部抛出异常,则从Cache 中获取数据

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

我有一个 spring 缓存要求:

我需要请求服务器获取一些数据并将结果存储在 spring 缓存中。同样的请求每次都会给我不同的结果,所以我决定使用@cachePut,这样每次我都可以进入我的函数并更新缓存。

@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
    }   
}

现在有一个转折点。如果服务器宕机而我无法得到响应;我想要缓存中的数据(存储在以前的请求中)。

如果我使用@Cacheable,我无法获取更新的数据。这样做的干净方法是什么?像捕获异常和 return 来自缓存的数据。

你可以像这样获取缓存实现并处理缓存。

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();
        }
    }
}