<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!--timeToIdleSeconds 當緩存閑置n秒后銷毀 -->
<!--timeToLiveSeconds 當緩存存活n秒后銷毀 -->
<!--
緩存配置
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:內存數量最大時是否清除。
statistics:是否收集統計信息。如果需要監控緩存使用情況,應該打開這個選項。默認為關閉(統計會影響性能)。設置statistics="true"開啟統計。
copyOnRead:當緩存項被讀出時,是否返回一份它的拷貝(返回對象是緩存中對象的拷貝)。默認false
copyOnWrite:當緩存項被寫入時,是否寫入一份它的拷貝(寫入緩存的是寫入對象的拷貝)。默認false。
-->
-
<diskStore path="java.io.tmpdir" /> <defaultCache maxElementsInMemory="500" eternal="false" timeToIdleSeconds="300" timeToLiveSeconds="1200" overflowToDisk="true" /> <cache name="com.Menu" maxElementsInMemory="150" eternal="false" timeToLiveSeconds="36000" timeToIdleSeconds="3600" overflowToDisk="true"/> </ehcache>
<!-- persistence : 子元素設置
persistence:表示Cache的持久化,它只有一個屬性strategy,表示當前Cache對應的持久化策略。其可選值如下:
localTempSwap:當堆內存或者非堆內存里面的元素已經滿了的時候,將其中的元素臨時的存放在磁盤上,一旦重啟就會消失。
localRestartable:該策略只對企業版Ehcache有用。它可以在重啟的時候將堆內存或者非堆內存里面的元素持久化到硬盤上,重啟之后再從硬盤上恢復元素到內存中。
none:不持久化緩存的元素
distributed:該策略不適用於單機,是用於分布式的。
copyStrategy:當我們指定了copyOnRead或copyOnWrite為true時,就會用到我們的copyStrategy,即拷貝策略了。默認的copyStrategy是通過序列化來實現的,我們可以通過實現net.sf.ehcache.store.compound.CopyStrategy接口來實現自己的CopyStrategy,然后只需在cache元素下定義一個copyStrategy元素並指定其class屬性為我們的CopyStrategy實現類。如:<copyStrategy class="xxx.xxx.xxx"/>。
pinning:表示將緩存內的元素固定住,除非過期,否則不會對它進行刪除和驅除到其它儲存容器中。pinning元素只定義了一個屬性store,表示將把元素固定在哪個位置。其可選值有localMemory和inCache。
localMemory:表示將元素固定在內存中。
inCache:表示將元素固定在任何其正在保存的容器中。
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> <!-- Cache configuration. The following attributes are required. name: Sets the name of the cache. This is used to identify the cache. It must be unique. maxElementsInMemory: Sets the maximum number of objects that will be created in memory (0 == no limit) maxElementsOnDisk: Sets the maximum number of objects that will be maintained in the DiskStore The default value is zero, meaning unlimited. eternal: Sets whether elements are eternal. If eternal, timeouts are ignored and the element is never expired. overflowToDisk: Sets whether elements can overflow to disk when the in-memory cache has reached the maxInMemory limit. The following attributes are optional. timeToIdleSeconds: Sets the time to idle for an element before it expires. i.e. The maximum amount of time between accesses before an element expires Is only used if the element is not eternal. Optional attribute. A value of 0 means that an Element can idle for infinity. The default value is 0. timeToLiveSeconds: Sets the time to live for an element before it expires. i.e. The maximum time between creation time and when an element expires. Is only used if the element is not eternal. Optional attribute. A value of 0 means that and Element can live for infinity. The default value is 0. diskPersistent: Whether the disk store persists between restarts of the Virtual Machine. The default value is false. diskExpiryThreadIntervalSeconds: The number of seconds between runs of the disk expiry thread. The default value is 120 seconds. diskSpoolBufferSizeMB: This is the size to allocate the DiskStore for a spool buffer. Writes are made to this area and then asynchronously written to disk. The default size is 30MB. Each spool buffer is used only by its cache. If you get OutOfMemory errors consider lowering this value. To improve DiskStore performance consider increasing it. Trace level logging in the DiskStore will show if put back ups are occurring. memoryStoreEvictionPolicy: Policy would be enforced upon reaching the maxElementsInMemory limit. Default policy is Least Recently Used (specified as LRU). Other policies available - First In First Out (specified as FIFO) and Less Frequently Used (specified as LFU) Cache elements can also contain sub elements which take the same format of a factory class and properties. Defined sub-elements are: * cacheEventListenerFactory - Enables registration of listeners for cache events, such as put, remove, update, and expire. * bootstrapCacheLoaderFactory - Specifies a BootstrapCacheLoader, which is called by a cache on initialisation to prepopulate itself. Each cache that will be distributed needs to set a cache event listener which replicates messages to the other CacheManager peers. For the built-in RMI implementation this is done by adding a cacheEventListenerFactory element of type RMICacheReplicatorFactory to each distributed cache's configuration as per the following example: <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" properties="replicateAsynchronously=true, replicatePuts=true, replicateUpdates=true, replicateUpdatesViaCopy=true, replicateRemovals=true "/> The RMICacheReplicatorFactory recognises the following properties: * replicatePuts=true|false - whether new elements placed in a cache are replicated to others. Defaults to true. * replicateUpdates=true|false - whether new elements which override an element already existing with the same key are replicated. Defaults to true. * replicateRemovals=true - whether element removals are replicated. Defaults to true. * replicateAsynchronously=true | false - whether replications are asynchronous (true) or synchronous (false). Defaults to true. * replicateUpdatesViaCopy=true | false - whether the new elements are copied to other caches (true), or whether a remove message is sent. Defaults to true. * asynchronousReplicationIntervalMillis=<number of milliseconds> - The asynchronous replicator runs at a set interval of milliseconds. The default is 1000. The minimum is 10. This property is only applicable if replicateAsynchronously=true * asynchronousReplicationMaximumBatchSize=<number of operations> - The maximum number of operations that will be batch within a single RMI message. The default is 1000. This property is only applicable if replicateAsynchronously=true The RMIBootstrapCacheLoader bootstraps caches in clusters where RMICacheReplicators are used. It is configured as per the following example: <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" properties="bootstrapAsynchronously=true, maximumChunkSizeBytes=5000000"/> The RMIBootstrapCacheLoaderFactory recognises the following optional properties: * bootstrapAsynchronously=true|false - whether the bootstrap happens in the background after the cache has started. If false, bootstrapping must complete before the cache is made available. The default value is true. * maximumChunkSizeBytes=<integer> - Caches can potentially be very large, larger than the memory limits of the VM. This property allows the bootstraper to fetched elements in chunks. The default chunk size is 5000000 (5MB). --> <diskStore path="java.io.tmpdir"/> <!-- Mandatory Default Cache configuration. These settings will be applied to caches created programmtically using CacheManager.add(String cacheName) --> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <persistence strategy="localTempSwap"/> </defaultCache> <cache name="cn.com.sina.dlfreebird.blog.cache" maxElementsInMemory="1000" maxElementsOnDisk="1000" overflowToDisk="true" eternal="true"> </cache> </ehcache>
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); } }