EhCache 不更新缓存

EhCache does not update cache

我在企业应用程序中将 EhCache v2.3.0 与 EclipseLink v2.5.2 和 EJB 3.0 结合使用。

问题是EhCache的对象没有更新。预期的行为是缓存在 60 秒后过期并重新加载数据。实际发生的是,缓存在 60 秒后过期并重新加载旧数据。

即使实体缓存设置为 'isolated',也会发生这种情况。出于测试目的,我什至将缓存类型设置为none,但它不起作用。

有人有想法吗?

这里是 ehcache.xml:

<ehcache name="testCache">
<defaultCache
    timeToIdleSeconds="60"
    timeToLiveSeconds="60"/>
<cache name="myCache"
    timeToIdleSeconds="60"
    timeToLiveSeconds="60"/></ehcache>

这是在上下文侦听器启动时正确加载的。所以缓存设置了正确的值,我在调试模式下检查过。

Cache 初始化后(它是一个 Singleton),用这个方法访问它:

/*
This method returns the current values in the cache as an list. 
If the elements expired, it gets the new values from the database, puts them into the cache and return them as list.
*/

public List<CacheEntries> getEntries() {

EhCache cache = cacheManager.getEhCache("myCache"); 
cache.evictExpiredElements();
List<CacheEntries> list = new ArrayList<CacheEntries>();

if(cache.getSize() == 0) {
    //get CacheEJB
    list = cacheEjb.getAll();
    for(CacheEntries e : list) {
        cache.put(new Element(e.getName(), e));
    }
}
else {
    Element element = null;
    List<String> keys = cache.getKeys();
    for(String s : keys) {
        element = cache.get(s);
        list.add((CacheEntries) element.getValue());
    }
}
return list;

}

因此实体被注释:

@Entity @Cache(type = CacheType.NONE, isolation = CacheIsolationType.ISOLATED) @Table ...

这个问题的原因不是EhCache而是JPA的二级缓存。要禁用整个 JPA 缓存,请添加到您的 persistence.xml

<persistence-unit name="ACME">
   <shared-cache-mode>NONE</shared-cache-mode>
</persistence-unit>

如果您想禁用特定实体的缓存,请使用 @Cacheable(false) 作为实体上的 class 注释。

也考虑不使用CacheType.NONE

Note, the CacheType NONE on the @Cache annotation should not be used to disable the cache, instead shared should be set to false. [EclipseLink/Examples/JPA/Caching]

作为最后一个选项,尝试通过查询提示触发缓存刷新。

Query query = em.createQuery("Select e from Employee e");
query.setHint("javax.persistence.cache.storeMode", "REFRESH");