java - ExpireAfterWrite 似乎不起作用

标签 java caching guava cache-expiration evict

我正在尝试使用 Google 的 Guava Cache,并且我只是以 1 分钟的间隔使用 expireAfterWrite 对其进行测试。在我正在开发的应用程序中,有数百个用户。所以我的理解是,当第一个人访问缓存时,我们从数据库中填充它,然后一分钟计时器应该开始倒计时。现在缓存已满。我们总是会在那一分钟的时间内从缓存中获取它。一分钟后,它就会过期,我们再次从数据库中获取它。

但是,似乎每次我在一分钟内访问缓存时,计时器都会重置。这是为什么?如果我在一分钟内没有访问缓存,缓存就会过期并正常工作。

代码:

 Cache<Long, List<someObj>> cacheMap = CacheBuilder.newBuilder().maximumSize(maxSize).expireAfterWrite(maxTime, TimeUnit.MINUTES).removalListener(new RemovalListener<Long, List<someObj>>() {
    public void onRemoval(RemovalNotification<Long, List<someObj>> notification) {
        if (notification.getCause() == RemovalCause.EXPIRED) {
            logger.info("Value " + notification.getValue() + " has been expired");
        } else {
            logger.info("Just removed for some reason");
        }
    }
}).build();

...
//Convert to ConcurrentHashMap
cacheMap = someCache.asMap();

...


public List<someObj> getAllData(final Long orgId, final User user) {
    // Get requests from cache
    List<Request> cacheList = overdueSlaMap.get(orgId);

    // Fill cached requests if null
    cacheList = fillCacheIfNecessary(orgId, cacheList, overdueSlaMap);  

    return cacheList;
}

//Strategy for reading and writing to cache
//This method is fine. On first load, cache is empty so we fill it from database. Wait one minute, value expires and cache is empty again so we get from cache. 
//However, everytime I refresh the page the one minute timer starts again. Surely, the one minute timer within the Guava Cache should not refresh regardless of how many times I access the cache within that one minute period. 
 private List<someObj> fillCacheIfNecessary(List<someObj> cacheList, ConcurrentMap<Long, List<someObj>> cacheMap) {

        // If the cache is empty then we will try to fill it from the database.
        if (cacheList == null) {
            logger.info("populating cache");
            List<someObj> objList = new ArrayList<someObj>();

            // if bla bla
            if (such and such) {
                objList = service.getFromDatabase(someArg);
            } else {
                objList = service.getFromDatabase(anotherarg);
            }

            // Concurrently lock the new cacheList retrieved from the database.
            List<someObj> newValue = Collections.unmodifiableList(objList);

            // Only insert if new value does not exist in cache map
            List<someObj> oldValue = cacheMap.putIfAbsent(orgId, newValue);

            // If old value already exists then we use the old value otherwise we use the new value
            cacheList = ((oldValue != null && !oldValue.isEmpty()) ? oldValue : newValue);
        }
        return cacheList;

    }

编辑

我从 Controller 调用缓存:

public ModelAndView getNotifications(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    User user = getCurrentUser();
    CacheManager cacheManager = new CacheManager();
    List<someObj> objList = new ArrayList<Request>();

    // Get from database
    if (bla bla) {
        objList = getFromDatabase(user);
    }
    // Get from cache
    else {
        Long orgId = user.getUserOrganisation().getId();
        objList = cacheManager.getAllData(orgId, user);      
    }

    return new ModelAndView(SOMEVIEW);
}

它将所需的有用数据传递给调用数据库的方法。然而,我现在尝试重构我的代码以使用 LoadingCache,但这需要我重写 load() 方法,该方法仅使用一个关键参数。我需要的不仅仅是 key ,我还需要调用 Controller 中的cacheManager,因此它会调用适当的方法。加载方法是什么?什么时候使用?什么时候调用以及多久调用一次?它会使我的其他方法失效吗?

最佳答案

我相信您的问题是您正在使用从 asMap 返回的 Map 作为缓存。 asMap 被记录为返回存储在该缓存中的条目 View 作为线程安全映射。这里没有任何内容表明您可以使用 Map 作为缓存。我建议更新您的代码以使用 Cache API 并直接在缓存上调用 putget(key, Callable)

您可能需要考虑使用 LoadingCache,因为我发现 API 更简单。

编辑

所以首先,只有当缓存中不存在该键时才会调用 load 方法。缓存调用 load 方法来获取应为其键返回的值,然后缓存该值以供下次使用。使用 CacheLoader 或 Callable 的好处之一是检索数据的调用是线程安全的,因为每个键仅调用一次,即使多个键也只调用一次对同一 key 的调用同时发生。

如果您需要传递更多信息,请创建一个包装对象,如下所示:

 public class MyKey{
       final Long orgId; // true key value
       final User user; // other values needed

       // implement equals and hashCode to ONLY use orgId. This will ensure that
       // the same cached value is returned for all requests with the same
       // orgId which is the ACTUAL key.
  }

您还可以使用常规Cache 执行相同的操作,并创建一个包含所需值的Callable

我建议 CacheLoader 使 fillCacheIfNecessary 无效。对 cache.get() 的简单调用将在内部确定该值是否必须检索或已存在于缓存中。它正在为您执行获取、检查是否为空、检索工作。

关于java - ExpireAfterWrite 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26909698/

相关文章:

java - 绘制位图最快的方法

java - 如何获取XML中的属性

Magento 无法重建缓存

multithreading - 线程系统如何处理被不同 CPU 缓存的共享数据?

java - Guava ImmutableSet.copyOf() 线程安全吗?

java - 如何在不同的线程中运行监听器或在不同的线程中进行计算

java - 访问/gcm-demo/sendAll。原因: HTTP Status Code: 401

java - 更改 jface 对话框的背景颜色

php - php 中的缓存方法?

java - google guava 缓存 invalidateAll() 和 cleanUp() 之间的区别