【问题标题】:Spring cache @Cacheable and @CachePut. If exception is thrown inside method of @cachePut, get data from CacheSpring缓存@Cacheable和@CachePut。如果@cachePut方法内部抛出异常,则从Cache中获取数据
【发布时间】:2019-12-09 14:56:54
【问题描述】:

我有一个弹簧缓存需求:

我需要向服务器请求获取一些数据并将结果存储在 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,我无法获取更新的数据。这样做的干净方法是什么?类似于捕获异常并从缓存中返回数据。

【问题讨论】:

    标签: spring spring-boot spring-cache


    【解决方案1】:

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

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

    【讨论】:

    • cache.get(url).get() 抛出空指针异常。但是当我调试时,我可以在缓存中看到我的数据。缓存-->存储-->可以看到我的数据
    • 当然,您必须先将值放入缓存中,然后才能从中获取。
    • 我的意思是我已经放置了缓存值。但检索该值给了我 NPE
    • 小修正,它对我有用: ConcurrentMap map = (ConcurrentMap)cache.getNativeCache();响应 = map.get(key);
    猜你喜欢
    • 2015-04-15
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多