ehcache基本使用示例

1. 简单说明

为什么使用缓存以及使用缓存的场景不做为本文要说明的东西,so,忽略,直接说重点。

虽然ehcache是缓存工具,和redis、memcache一样都提供有缓存的功能,but,它是一个进程内缓存工具,当然它也支持分布式缓存,不过,对于使用分布缓存的场景,我个人建议放弃它。

但是,在需要使用本地缓存的时候,ehcache是一个很好用的工具,它比redis这些外存工具,具有更快的读写速度,并且也提供了丰富的功能,最主要的是,简单,易上手,功能强大。

闲话少说,需要详细了解建议去看官网文档,是第一次用,想入个门,往下看。

2. 几个重要的类

2.1 CacheManager

简单的说,这个类是用来管理缓存(Cache)的,它支持单例,也支撑用new实例化。

获取这个类的实例,有如下几种方式:

  1. 默认加载类路径下的ehcache.xml配置

CacheManager manager = CacheManager.create();
CacheManager manager = new CacheManager();

上面这两种方式是默认从类路径下加载ehcache.xml配置来初始化,关于这个配置可以看第3节。

    2. 指定配置文件位置

// 方式1指定文件位置
CacheManager manager = new CacheManager("src/config/ehcache.xml");
// 方式2作为类路径下的资源加载
CacheManager manager = new CacheManager(Thread.currentThread().getClass().getResource("/ehcache.xml"))
  // 方式3以输入流的方式
try(InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath())) {
CacheManager manager = new CacheManager(fis);
}

2.2 Cache

从CacheManager里获取,这可以看作是一个缓存区域,每个区域互不影响,用一个name来标识,也用这个name从CacheManager获取。

比如,在ehcache.xml里定义了一个cache,name是demoCache,获取的代码就是这样:

Cache demoCache = cacheManage.getCache("demoCache");

ps.这个cache不一定非要在ehcache.xml里定义,可以动态添加的,具体看第4节说明

2.3 Element

这个可以看做是一个缓存(Cache)的原子元素了,从Cache里CRUD,有一个key、value和一个访问记录标识。默认是可以用k,v实例化,然后存入Cache.如下:

cache.put(new Element(key, value));

3. ehcache.xml

先给一个官方标准的ehcache.xml文件:http://www.ehcache.org/ehcache.xml

这上面列出了所有配置项及具体说明以及一些示意配置,本文只对其中几项做简单说明,示例配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

    <!-- 磁盘缓存位置 -->
    <diskStore path="user.dir/ehcache"/>

    <!-- 默认缓存 -->
    <defaultCache
            maxEntriesLocalHeap="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxEntriesLocalDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <!-- demoCache缓存 -->
    <cache name="demoCache"
           maxElementsInMemory="1000"
           eternal="false"
           timeToIdleSeconds="5000"
           timeToLiveSeconds="5000"
           diskPersistent="true"
           overflowToDisk="false"
           memoryStoreEvictionPolicy="LRU"/>
</ehcache>
  1. diskStore磁盘缓存位置,如果有至少1个需要磁盘持久化,那就显示配置这个位置,默认使用的是java.io.tmpdir,临时文件路径,我的示例用的是user.dir,也就是工程路径,当然还可以用user.home:用户路径或者通过VM参数设置的路径:-Dehcache.disk.store.dir=/..这些。

  2. name:这个标识这个缓存区域的名称,从CacheManager这里获取这个缓存区域也是用这个标识

  3. maxElementsInMemory :内存中允许存储的最大的元素个数,0代表无限个

  4. eternal:设置缓存中对象是否为永久的,默认为false,如果为true表示永远有效,timeToIdleSeconds和timeToLiveSeconds不生效

  5. timeToIdleSeconds:缓存中对象闲置时间,这个值应当小于timeToLiveSeconds

  6. timeToLiveSeconds:对象存活周期,超时存活时间会被回收

  7. diskPersistent:是否持久化到磁盘,如果持久化到磁盘,重启的时候未过期的缓存对象可是还会加载回来的噢

  8. overflowToDisk:内存不足时,是否启用磁盘缓存

  9. memoryStoreEvictionPolicy:内存回收算法,比如缓存对象回收策略,有LRU,LFU,FIFO.

p.s.磁盘回收策略默认用的是LRU噢。

4. 动态增加缓存及刷新配置

4.1 动态增加缓存

这个直接给个官方的示例代码吧:

//Create a CacheManager using defaults
CacheManager manager = CacheManager.create();
//Create a Cache specifying its configuration.
Cache testCache = new Cache(
new CacheConfiguration("test", maxElements)
.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
.overflowToDisk(true)
.eternal(false)
.timeToLiveSeconds(60)
.timeToIdleSeconds(30)
.diskPersistent(false)
.diskExpiryThreadIntervalSeconds(0));
manager.addCache(cache);

 

4.2 动态修改配置

示例如下:

Cache cache = manager.getCache("demoCache");
CacheConfiguration config = cache.getCacheConfiguration();
config.setTimeToIdleSeconds(2);
config.setTimeToLiveSeconds(100);
config.setMaxElementsInMemory(1000);

另外,可以禁用动态修改配置:

cache.disableDynamicFeatures();

5. 示例代码

下面是一个基本的示例代码,

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

public class Demo {

    public static void main(String[] args) throws InterruptedException {
      // 实例化一个CacheManager默认从类路径下加载ehcahe.xml
        CacheManager  cacheManager = CacheManager.create();
      // 获取demoCache
        Cache cache = cacheManager.getCache("demoCache");
      // 实例一个元素,Element有多个构造方法,可以根据需要实例化
        Element element = new Element("name", "demo");
      // 把这个元素放到demoCache
        cache.put(element);
        Element value = cache.get("name");
      // 这个要注意,如果设置磁盘持久化,这个操作,会实时的将该缓存刷到磁盘,如果未设置,元素就刷没有了
        //cache.flush();
        cacheManager.shutdown();
    }
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不识君的荒漠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值