EhCache使用心得

在开发高并发量,高性能的网站应用系统时,缓存Cache起到了非常重要的作用。本文主要介绍EHCache的使用,以及使用EHCache的实践经验。

1、配置ehcache.xml,不配置将使用默认,建议配置!

 <ehcache updateCheck="false" dynamicConfig="false">
    <diskStore path="D:/test/ehcache"/>
    <defaultCache
        maxElementsInMemory="1000"
        eternal="false"
        overflowToDisk="true"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120"
    />    
   
    <cache name="topCache"
        maxElementsInMemory="10"
        eternal="false"
        timeToIdleSeconds="60"
        timeToLiveSeconds="60"
        overflowToDisk="true"
   /> 

   <cache name="msgCache"
        maxElementsInMemory="10"
        eternal="true"
        timeToIdleSeconds="120"
        timeToLiveSeconds="120"
        overflowToDisk="true"
        diskPersistent="true"
   />
</ehcache> 

然后将文件防止在项目的src目录下,因为下面在创建CacheManager没有指定ehcache.xml路径,那么将使用默认classpath目录下的。

各配置参数的含义:
maxElementsInMemory:缓存中允许创建的最大对象数
eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0 就意味着元素可以停顿无穷长的时间。
timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
overflowToDisk:内存不足时,是否启用磁盘缓存。

diskPersistent 是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名为cache名称,后缀名为index的文件

memoryStoreEvictionPolic

y:缓存满了之后的淘汰算法。LRU和FIFO算法这里就不做介绍。LFU算法直接淘汰使用比较少的对象,在内存保留的都是一些经常访问的对象。对于大部分网站项目,该算法比较适用。
如果应用需要配置多个不同命名并采用不同参数的Cache,可以相应修改配置文件,增加需要的Cache配置即可。

2、测试代码

// 使用默认配置文件创建CacheManager
CacheManager manager = CacheManager.create();
// 通过manager可以生成指定名称的Cache对象
Cache cache = cache = manager.getCache("msgCache");

可以通过调用manager.removalAll()来移除所有的Cache。通过调用manager的shutdown()方法可以关闭CacheManager。
有了Cache对象之后就可以进行一些基本的Cache操作,例如:
//往cache中添加元素
Element element = new Element("key", "value");
cache.put(element);
//从cache中取回元素
Element element = cache.get("key");
System,out.println(element.getValue());
//从Cache中移除一个元素
cache.remove("key");
<pre name="code" class="java">// 使用manager移除指定名称的Cache对象
manager.removeCache("msgCache");



打印结果 value

查看

D:/test/ehcache
是否生成缓存


原文地址:https://www.cnblogs.com/xieyuan/p/3787243.html