Ehcache的应用

来源:互联网 发布:模糊图片修复软件 编辑:程序博客网 时间:2024/05/29 17:03

Ehcache

简介
Ehcache是一个纯java的进程内缓存框架,具有快速、精干等特点,同时它也是Hibernate中默认的缓存方案。

主要的特性有:
1. 快速.
2. 简单.
3. 多种缓存策略
4. 缓存数据有两级:内存和磁盘,因此无需担心容量问题
5. 缓存数据会在虚拟机重启的过程中写入磁盘
6. 可以通过RMI、可插入API等方式进行分布式缓存
7. 具有缓存和缓存管理器的侦听接口
8. 支持多缓存管理器实例,以及一个实例的多个缓存区域
9. 提供Hibernate的缓存实现

应用
ehcache的配置文件:

<?xml version="1.0" encoding="UTF-8"?> <ehcache>  <!-- maxElementsInMemory设定内存中创建对象的最大值 --><!-- eternal设置元素(译注:内存中对象)是否永久驻留。如果是,将忽略超 时限制且元素永不消亡。-->  <!-- overflowToDisk设置当内存中缓存达到 maxInMemory 限制时元素是否可写到磁盘上 -->  <!-- timeToIdleSeconds设置某个元素消亡前的停顿时间。  也就是在一个元素消亡之前,两次访问时间的最大时间间隔值。               这只能在元素不是永久驻留时有效(译注:如果对象永恒不灭,则 设置该属性也无用)。         如果该值是 0 就意味着元素可以停顿无穷长的时间。                                   -->  <!-- timeToLiveSeconds为元素设置消亡前的生存时间。 也就是一个元素从构建到消亡的最大时间间隔值。 这只能在元素不是永久驻留时有效。 -->  <!-- diskPersistent是否disk store在虚拟机启动时持久化。默认为false -->  <!-- diskExpiryThreadIntervalSeconds运行disk终结线程的时间,默认为120秒 -->      <defaultCache          maxElementsInMemory="10000"           eternal="false"           overflowToDisk="true"           timeToIdleSeconds="500"           timeToLiveSeconds="1000"           diskPersistent="false"           diskExpiryThreadIntervalSeconds="120"/>        <!-- 测试 -->      <cache           name="cache_test"        memoryStoreEvictionPolicy="LRU"           maxElementsInMemory="10"           eternal="false"          timeToIdleSeconds="7200"          timeToLiveSeconds="7200"           overflowToDisk="true" /> </ehcache>  

Ehcache的工具类

/** * Ehcache工具类 * */public class EhcacheUtil {    private static final String path = "src/main/java/configuration/ehcache.xml";    private static CacheManager cacheManager;    /**     * 创建一个缓存管理器     */    public static CacheManager getCacheManager() {        if (cacheManager == null) {            cacheManager = CacheManager.create(path);        }        return cacheManager;    }    /**     *放入缓存      */    public static void putCache(String cachename, Object key, Object value) {        put(cachename, key, value);    }    /**     * 获取缓存     */    public static Object getCacheValue(String cachename, Object key) {        return getCache(cachename).get(key).getObjectValue();    }    public static void removeCache(String cachename, Object key) {        remove(cachename, key);    }    /**     *获取一个chache      */    private static Cache getCache(String cachename) {        cacheManager = getCacheManager();        Cache cache = cacheManager.getCache(cachename);        if (cache == null) {            cacheManager.addCache(cachename);            cache = cacheManager.getCache(cachename);            cache.getCacheConfiguration().setEternal(true);             //放置在缓存中的对象永不过期        }        return cache;    }    /**     * 放置缓存的私有方法     */    private static void put(String cachename, Object key, Object value) {        Element element = new Element(key, value);        getCache(cachename).put(element);    }    /**     * 移除缓存的私有方法     */    private static void remove(String cachename, Object key) {        getCache(cachename).remove(key);    }}

在这里没有用到数据库,所以编写了一个自带数据集合的一个类,用来替代:

public class PersonManagerImpl {      private static List<String> persons;      static {          persons = new ArrayList<String>();          persons.add("Wang");          persons.add("zang");          persons.add("Li");          persons.add("song");          persons.add("yan");      }      public List<String> getList() {          return persons;      }  }  

配置文件和工具类编写完毕,下面进行测试

public class AppTest{    static CacheManager cacheManager = EhcacheUtil.getCacheManager();    @Test    public void test() {        PersonManagerImpl personManagerImpl = new PersonManagerImpl();        for (int i = 0; i <3; i++) {            if (i == 2) {                EhcacheUtil.removeCache("cache_test", 1);            }            showinfo(personManagerImpl);        }    }    public void showinfo(PersonManagerImpl personManagerImpl) {        Cache cache = cacheManager.getCache("cache_test");        if (cache.get(1) == null) {            System.out.println("from DB");            List<String> infos = personManagerImpl.getList();            for (String s : infos) {                System.out.println(s);            }            putCache();        } else {            System.out.println("from cache");            List<String> list =         (List<String>)EhcacheUtil.getCacheValue("cache_test", 1);            for (String s : list) {                System.out.println(s);            }        }    }    public void putCache() {        PersonManagerImpl personManagerImpl = new PersonManagerImpl();        EhcacheUtil.putCache("cache_test", 1, personManagerImpl.getList());    }

下面是测试输出结果:

原创粉丝点击