码迷,mamicode.com
首页 > 系统相关 > 详细

Ehcache配置详解及CacheManager使用

时间:2017-10-26 19:02:16      阅读:214      评论:0      收藏:0      [点我收藏+]

标签:app   清理内存   false   loader   ber   sts   tca   最大   man   

<?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。


-->

Java代码  
  1. <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工具类使用:

Java代码  
      1. 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);  
            }  
          
        }  

         

Ehcache配置详解及CacheManager使用

标签:app   清理内存   false   loader   ber   sts   tca   最大   man   

原文地址:http://www.cnblogs.com/yuluoxingkong/p/7738276.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!