ehcache是一个纯Java进程内缓存框架,是hibernate默认的Cacheprovider。(出自百度百科)。

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

⑴、简单代码实现:

配置文件2个ehcache.xml 、ehcache.xsd

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="true" monitoring="autodetect"
dynamicConfig="true">
<diskStore path="d:/file"/>
<cache name="ehcache1"
maxElementsInMemory="100"
maxElementsOnDisk="0"
eternal="false"
timeToIdleSeconds="300000"
timeToLiveSeconds="300000"
diskPersistent="true"
overflowToDisk="true"
/> </ehcache>

demo调用:

这种调用方式若属性配置了虚拟机重启缓存数据将会报错:

package com.jws.app.junt;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
* ehcache框架测试
* @author Administrator
*
*/
public class ehcacheDemo {
public static void main(String[] args) {
//CacheManager manager1 = CacheManager.newInstance("src/config/ehcache1.xml");
CacheManager manager = CacheManager.create();
Cache cache = manager.getCache("ehcache1");
// manager.addCache("ehcache2");
//Cache test = manager.getCache("ehcache2");
cache.put(new Element("key1", "values1"));
cache.put(new Element("key2", "values2"));
cache.put(new Element("key3", "values3"));
Element element = cache.get("key1");
System.out.println(element.getValue());
cache.flush();
} }

    配置文件详解:

maxElementsInMemory:    内存中允许缓存的最大数量,若超过这个数量,数据将缓存在磁盘。

maxElementsOnDisk:   硬盘中缓存的最大数量,0表示无限大。

    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:内存数量最大时是否清除。

    

以下属性是可选的:
timeToIdleSeconds: 对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问。
timeToLiveSeconds: 对象存活时间,指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问。
diskPersistent: 是否在磁盘上持久化。指重启jvm后,数据是否有效。默认为false。
diskExpiryThreadIntervalSeconds: 对象检测线程运行时间间隔。标识对象状态的线程多长时间运行一次。
diskSpoolBufferSizeMB: DiskStore使用的磁盘大小,默认值30MB。每个cache使用各自的DiskStore。
memoryStoreEvictionPolicy:
如果内存中数据超过内存限制,向磁盘缓存时的策略。默认值LRU,可选FIFO、LFU。
 
缓存的3 种清空策略
FIFO ,first in first out (先进先出).
LFU , Less Frequently Used (最少使用).意思是一直以来最少被使用的。缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存。
LRU ,Least Recently Used(最近最少使用). (ehcache 默认值).缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.sf.net/ehcache.xsd"> <diskStore path="d:/file" /> <defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="10"
timeToLiveSeconds="20"
diskPersistent="false" /> <cache name="requestCache"
maxElementsInMemory="100000"
eternal="false"
overflowToDisk="false"
timeToIdleSeconds="180"
timeToLiveSeconds="180"
diskPersistent="false"
memoryStoreEvictionPolicy="LFU" /> <cache name="myCache"
maxElementsInMemory="2"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="180"
timeToLiveSeconds="180"
maxElementsOnDisk="0"
diskPersistent="true"
memoryStoreEvictionPolicy="LFU" />
</ehcache>
package com.jws.app.junt;

import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
* ehcache框架测试
* @author Administrator
*
*/
public class ehcacheDemo {
public static void main(String[] args) {
// 指定ehcache.xml的位置
String fileName = "src/main/resources/ehcache.xml";
CacheManager manager = new CacheManager(fileName);
// 取出所有的cacheName
Cache cache = manager.getCache("myCache");
System.out.println(cache.getSize());
//获取单个节点
Element el = cache.get("key1812");
System.out.println("【单个节点】"+el.getValue());
el = cache.get(1);
//System.out.println("【单个节点2】"+el.getValue());
List<Element> cl = cache.getKeys();
// cl.size(); //
// for(int i=0;i<1000;i++){
// cache.put(new Element("key1"+ i , "values1"+i));
// }
// // cache.flush(); manager.shutdown();
}
}
package com.jws.common.util;

import java.util.List;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element; /**
* EHcache工具类 
* @author Administrator
*
*/
public class EHCacheConfig { /**
* 当前采用的缓存对象
*/
public static String cacheObject = "myCache";
private static CacheManager cacheManager = null;
private static Cache cache = null; static{
EHCacheConfig.initCacheManager();
EHCacheConfig.initCache();
} /**
*
* 初始化缓存管理容器
*/
public static CacheManager initCacheManager() {
try {
if (cacheManager == null)
System.out.println("【EHcache start............】");
cacheManager = CacheManager.getInstance();
} catch (Exception e) {
e.printStackTrace();
}
return cacheManager;
} /**
* 初始化cache
* @return
*/
public static Cache initCache() {
if(cache ==null){
cache = cacheManager.getCache("myCache");
System.out.println("【EHcache cache start............】");
}
return cache;
}
/**
*
* 添加缓存
*
* @param key
* 关键字
* @param value
* 值
*/
public static void put(Object key, Object value) {
// 创建Element,然后放入Cache对象中
Element element = new Element(key, value);
cache.put(element);
} /**
* 获取cache
*
* @param key
* 关键字
* @return
*/
public static Object get(Object key) {
Element element = cache.get(key);
if (null == element) {
return null;
}
return element.getObjectValue();
}
/**
* 移除所有cache
*/ /**
* 释放CacheManage
*/ public static void shutdown() {
cacheManager.shutdown();
} public static void removeAllCache() {
cacheManager.removalAll();
}
/**
*
* 移除所有Element
*/
public static void removeAllKey() {
cache.removeAll();
}
/**
*
* 获取所有的cache名称
* @return
*/
public static String[] getAllCaches() {
return cacheManager.getCacheNames();
}
/**
*
* 获取Cache所有的Keys
* @return
*/
public static List<Element> getKeys() {
return cache.getKeys();
} }

【Java】:ehcache的更多相关文章

  1. 【Java】:压缩成多个压缩卷

    Java自带的库不支持压缩成多个压缩卷,找到了一个开源库 zip4j ,发现更好用 so easy package com.jws.common.mail; import java.io.File; ...

  2. 【Java】:googleSearch

    google custom search是一个基于google的搜索引擎api,可以请求谷歌的搜索数据 pala pala  pala  ... 实现: 1.注册谷歌账号 2.创建google项目 1 ...

  3. 【java】:通用小知识

    1.将String字符串放在最前面 为了防止偶发性的NullPointerException 异常,我们通常将String放置在equals()函数的左边来实现字符串比较,如下代码: // Bad i ...

  4. 【java】:解析xml

    ==========================================xml文件<?xml version="1.0" encoding="GB231 ...

  5. 【java】: 操作excel2007/2003

    //上传位置(与操作excel无关,可不看) public String getUploadPath() { File theWebFolder = XMPPServer.getInstance(). ...

  6. 【java】:生成excel

    //生成报表公用方法 //excelName: 生成的文件名 //list:时间/日期/描述 //listSelectFiled:  标题 //showContent :  文件内容bean //生成 ...

  7. 【java】:常用工具类

    PS; 平时用到的一些工具类,验证非空.字符切割.时间转换.金额转换 package com.jws.common.util; import java.io.UnsupportedEncodingEx ...

  8. 【java】:读取文件

    PS:转 1.按字节读取文件内容2.按字符读取文件内容3.按行读取文件内容4.随机读取文件内容 public class ReadFromFile { /** * 以字节为单位读取文件,常用于读二进制 ...

  9. 【java】:定时任务

    PS:转 http://blog.csdn.net/lotusyangjun/article/details/6450421/

随机推荐

  1. 利用循环播放dataurl的视频来防止锁屏:NoSleep.js

    mark下. 地址:http://www.open-open.com/lib/view/open1430796889882.html

  2. HTML中图片添加

    图片添加后保存的是添加路径 例: <div class="form-group"> <label class="col-sm-3 control-lab ...

  3. SQL、Linq、lamda表达式 同一功能不同写法

    一.SQL.Linq.lamda表达式 同一功能不同写法 SQL LINQ Lambda SELECT * FROM HumanResources.Employee from e in Employe ...

  4. npm库下载缓慢解决方案

    淘宝针对国内下载npm库缓慢的问题,使用建立自己的cnpm库,可以很方便使用在公司内部使用. 地址:http://npm.taobao.org/ $ npm install -g cnpm --reg ...

  5. 初识Android NDK

    本文介绍Windows环境下搭建Android NDK开发环境,并创建一个简单的使用Native代码的Android Application. 一.环境搭建 二.JNI函数绑定 三.例子 一.环境搭建 ...

  6. Spring里PropertyPlaceholderConfigurer类的使用

    1. PropertyPlaceholderConfigurer是个bean工厂后置处理器的实现,也就是 BeanFactoryPostProcessor接口的一个实现.PropertyPlaceho ...

  7. myeclipse ctrl + 鼠标单击 出现 source not found

    有时候我们下载来目录中有一个src文件夹,里面是源代码,而不是打包好的jar或zip文件.src目录下的源代码是按照包结构存放的,比如a.java的第一行是package test; 那么在src/t ...

  8. UICollectionReusableView 使用时的一些问题

    在使用UICollectionView 时, 设置分区头时, - (UICollectionReusableView *)collectionView:(UICollectionView *)coll ...

  9. 使用JSONObject遇到的问题,java.lang.NoClassDefFoundError: net/sf/json/JSONObject

    先是报 java.lang.NoClassDefFoundError: net/sf/json/JSONObject 这个错误, 打开项目属性找到java build path中的libaries,找 ...

  10. Office 365 系列二 ------- 如何批量部署Office 客户端

    针对于第一篇文章所讲的,我们最用使用用户可以单个点击进行安装,但是如果我们终端用户太多的情况,不可能大家都点击单个文件进行安装了,这样子既耗费时间也耗费 公司的网络带宽,那么我们可以采取离线下载的方式 ...