【问题标题】:configure object level caching in ehcache在 ehcache 中配置对象级缓存
【发布时间】:2015-01-06 00:09:58
【问题描述】:

有没有办法在 ehcache 中配置对象或类级别的缓存(每个都有不同的设置)?我正在使用 java+spring+mybatis 堆栈。

另外,什么是 ehcache 等价于以下基于 oscache 的实现?

public Map<Integer, ProductDetails> getProductDetails(final List<Integer> productIds)
throws Exception{
    Map<Integer, ProductDetails> result = null;

    try{
        //Get from cache.
        result = (Map<Integer, ProductDetails>) cache.getFromCache("AllProductDetails");

        if(result == null){
            throw new NeedsRefreshException("Cache needs a refresh!");
        }
    }
    catch(final NeedsRefreshException nre){
        try{
            result = ProductDetailsDao.getProductDetails("");
            cache.putInCache("AllProductDetails", result);
        }
        catch (final Exception e){
            result = (Map<Integer, ProductDetails>) nre.getCacheContent();
            cache.cancelUpdate("AllProductDetails");
        }
    }
    return result;
}

我发现 ehcache 中没有 com.opensymphony.oscache.base.NeedsRefreshException 的等价物。

识别特定对象的数据是否已过期或该对象根本不存在于缓存中的推荐方法是什么?

【问题讨论】:

  • 你为什么不简单地使用 Spring Cache Abstraction?这将为您节省大量样板代码...
  • 感谢Deinum 的回复。我怎么做?能给个链接吗?
  • Spring 参考指南中有一个关于caching 的部分。

标签: java spring caching ehcache


【解决方案1】:

您需要在 EHcache 对象上调用 getCacheConfiguration。然后你可以修改它的fields

以下是一些检查过期或缺失的示例代码。请注意使用getQuiet,以确保您不会通过查看来重置到期时间。

  public boolean expired(final K key) {
      boolean expired = true;
      // Do a quiet get so we don't change the last access time.
      final Element element = cache.getQuiet(key);
      if (element != null) {
        expired = cache.isExpired(element);
        if (expired) {
          log.trace("Expired because expired.");
        } else {
          expired = element.getObjectValue() == null;
          if (expired) {
            log.trace("Expired because value null.");
          }
        }
      } else {
        log.trace("Expired because not present.");
      }
      return expired;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 2016-06-05
    • 2016-04-23
    相关资源
    最近更新 更多