ehcache 缓存的常用配置

前言

Ehcache,小型轻量
但现在笔者缓存方面,基本都是使用 Redis,更加方便、性能更好
下面是之前的总结代码,留着,说不定其他团队、公司在用

代码

这里写图片描述

Test

package ehc;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

public class Test {
    public static void main(String[] args) {

        // 根据ehcache.xml配置文件创建Cache管理器
        CacheManager manager = CacheManager.create("./src/main/resources/ehcache.xml");

        // 获取指定cache
        Cache c = manager.getCache("a");
        Element e = new Element("linhongcun", "larger666");

        // 把一个元素添加到Cache中
        c.put(e);

        // 根据key获取缓存元素
        Element e2 = c.get("linhongcun");
        System.out.println(e2);

        // 刷新缓存
        c.flush();

        // 关闭缓存管理器,释放内存
        manager.shutdown();

    }
}

xml

<?xml version="1.0" encoding="UTF-8"?>

<ehcache>
   <!--
         磁盘存储:将缓存中暂时不使用的对象,转移到硬盘,类似于Windows系统的虚拟内存
          path:指定在硬盘上存储对象的路径
   -->
   <diskStore path="C:\LLLLLLLLLLLLLLLLLLL\ehcache" />

   <!--
        defaultCache:默认的缓存配置信息,如果不加特殊说明,则所有对象按照此配置项处理
        maxElementsInMemory:设置了缓存的上限,最多存储多少个记录对象,超出的话才会存储到本地目录下!!
        eternal:代表对象是否永不过期
        overflowToDisk:当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中
   -->
   <defaultCache
      maxElementsInMemory="100"
      eternal="true"
      overflowToDisk="true"/>

    <!-- 下面的自定义cache会继承defaultCache,overwrite罢了 -->
    <cache
      name="a"
      maxElementsInMemory="100"
      eternal="true"
      overflowToDisk="true"/>

</ehcache>

POM

        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.4</version>
        </dependency>

其他

属性说明:
diskStore:指定数据在磁盘中的存储位置。
defaultCache:当借助CacheManager.add(“demoCache”)创建Cache时,EhCache便会采用指定的的管理策略

以下属性是必须的:
maxElementsInMemory - 在内存中缓存的element的最大数目
maxElementsOnDisk - 在磁盘上缓存的element的最大数目,若是0表示无穷大
eternal - 设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断
overflowToDisk - 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上

以下属性是可选的:
timeToIdleSeconds - 当缓存在EhCache中的数据前后两次访问的时间超过timeToIdleSeconds的属性取值时,这些数据便会删除,默认值是0,也就是可闲置时间无穷大
timeToLiveSeconds - 缓存element的有效生命期,默认是0.,也就是element存活时间无穷大
diskSpoolBufferSizeMB 这个参数设置DiskStore(磁盘缓存)的缓存区大小.默认是30MB.每个Cache都应该有自己的一个缓冲区.
diskPersistent - 在VM重启的时候是否启用磁盘保存EhCache中的数据,默认是false。
diskExpiryThreadIntervalSeconds - 磁盘缓存的清理线程运行间隔,默认是120秒。每个120s,相应的线程会进行一次EhCache中数据的清理工作
memoryStoreEvictionPolicy - 当内存缓存达到最大,有新的element加入的时候, 移除缓存中element的策略。默认是LRU(最近最少使用),可选的有LFU(最不常使用)和FIFO(先进先出)

猜你喜欢

转载自blog.csdn.net/larger5/article/details/79874610