2016-05-23 209 views
4

我在企業應用程序中將EhCache v2.3.0與EclipseLink v2.5.2和EJB 3.0結合使用。EhCache不更新緩存

問題是,EhCache的對象沒有更新。預期的行爲是,緩存在60秒後過期並重新加載數據。實際情況是,緩存在60秒後過期並重新加載舊數據。

即使實體緩存設置爲「隔離」,也會發生這種情況。出於測試目的,我甚至將緩存類型設置爲none,但它不起作用。

有沒有人有想法?

這裏是ehcache.xml中:

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

這是在上下文監聽器的啓動負載正常。所以緩存設置正確的值,我已經在調試模式檢查。

/* 
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 ... 
+0

另外添加一個緩存事件監聽器是一種好的做法。你可以真正確定發生了什麼。 http://www.ehcache.org/documentation/2.8/apis/cache-event-listeners.html –

回答

1

其原因

緩存得到initilized(它是一個單件)後,它與這種方法訪問問題不是EhCache它是JPA的二級緩存。要禁用整個JPA緩存添加到您的persistence.xml

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

如果要禁用緩存爲你的實體特定實體使用@Cacheable(false)爲類註解。

也考慮不要使用CacheType.NONE

請注意,不應使用@Cache批註中的CacheType NONE來禁用緩存,而應將共享設置爲false。 [EclipseLink/Examples/JPA/Caching]

作爲最後一個選項嘗試通過查詢提示觸發緩存刷新。

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

解決 - 非常感謝! –