ehcache 緩存學習使用總結

ehcache 緩存學習使用總結

1.緩存配置

name:緩存名稱。

maxElementsInMemory:緩存最大個數。

eternal:對象是否永久有效,一但設置了,timeout將不起作用。

timeToIdleSeconds:設置對象在失效前的允許閒置時間(單位:秒)。僅當eternal=false對象不是永久有效時使用,可選屬性,默認值是0,也就是可閒置時間無窮大。

timeToLiveSeconds:設置對象在失效前允許存活時間(單位:秒)。最大時間介於創建時間和失效時間之間。僅當eternal=false對象不是永久有效時使用,默認是0.,也就是對象存活時間無窮大。

overflowToDisk:當內存中對象數量達到maxElementsInMemory時,Ehcache將會對象寫到磁盤中。

diskSpoolBufferSizeMB:這個參數設置DiskStore(磁盤緩存)的緩存區大小。默認是30MB。每個Cache都應該有自己的一個緩衝區。

maxElementsOnDisk:硬盤最大緩存個數。

diskPersistent:是否緩存虛擬機重啓期數據 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.

diskExpiryThreadIntervalSeconds:磁盤失效線程運行時間間隔,默認是120秒。

memoryStoreEvictionPolicy:當達到maxElementsInMemory限制時,Ehcache將會根據指定的策略去清理內存。默認策略是LRU(最近最少使用)。你可以設置爲FIFO(先進先出)或是LFU(較少使用)。

clearOnFlush:內存數量最大時是否清除。

2.ehcache.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="hibernateCache">

    <diskStore path="java.io.tmpdir/ehcache/hibernateCache" />

    <!-- DefaultCache setting. -->
    <defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="600"
        overflowToDisk="true" maxEntriesLocalDisk="100000" />

</ehcache>

3.EhcacheUtil類

public class EhcacheUtil {  

    private static final String path = "/ehcache.xml";  

    private URL url;  

    private CacheManager manager;  

    private static EhcacheUtil ehCache;  

    private EhcacheUtil(String path) {  
        url = getClass().getResource(path);  
        manager = CacheManager.create(url);  
    }  

    public static EhcacheUtil getInstance() {  
        if (ehCache== null) {  
            ehCache= new EhcacheUtil(path);  
        }  
        return ehCache;  
    }  

    public void put(String cacheName, String key, Object value) {  
        Cache cache = manager.getCache(cacheName);  
        Element element = new Element(key, value);  
        cache.put(element);  
    }  

    public Object get(String cacheName, String key) {  
        Cache cache = manager.getCache(cacheName);  
        Element element = cache.get(key);  
        return element == null ? null : element.getObjectValue();  
    }  

    public Cache get(String cacheName) {  
        return manager.getCache(cacheName);  
    }  

    public void remove(String cacheName, String key) {  
        Cache cache = manager.getCache(cacheName);  
        cache.remove(key);  
    }  

}

4.Spring+EhCache緩存

<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation">
        <value>classpath:cache/ehcache-spring.xml</value>
    </property>
    <!-- 由於hibernate也使用了Ehcache, 保證雙方都使用同一個緩存管理器 -->
    <property name="shared" value="true"/>
</bean> 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章