EHcache二级缓存,谁用过Hibernate二级缓存的同学,对于二级缓存这东东都知道一二,是干嘛用的,在这不多说。这里简答介绍EHcache的用法,以及写个小例子,模拟对象增删改查时,对象的缓存过程,对ehcache有过初步的了解。
ehcache元素属性:
- name:缓存名称
- maxElementsInMemory:内存中最大缓存对象数
- maxElementsOnDisk:硬盘中最大缓存对象数,若是0表示无穷大
- eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false
- overflowToDisk:true表示当内存缓存的对象数目达到了maxElementsInMemory界限后,会把溢出的对象写到硬盘缓存中。注意:如果缓存的对象要写入到硬盘中的话,则该对象必须实现了Serializable接口才行。
- diskSpoolBufferSizeMB:磁盘缓存区大小,默认为30MB。每个Cache都应该有自己的一个缓存区
- diskPersistent:是否缓存虚拟机重启期数据
- diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认为120秒
- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态
- timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了 timeToLiveSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义
- memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)
ehcache配置常用的一些元素介绍完了,下面来个完整的简单例子看看。
项目结构图:
bean下的Studnet.java,School.java模拟领域对象,允许二级缓存缓存它们;如果配置中允许缓存数超过最大缓存数时,将对象写入磁盘的话,则领域对象需要实现序列化。
dao模拟操作数据库,增删改查。
database模拟数据库中的数据
util工具对象,EHcacheUtil二级缓存工具,ehcache.xml配置文件.
下面贴源码:
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!-- 指定一个文件目录,当EHCache把数据写到硬盘上时,将把数据写到这个文件目录下 -->
<diskStore path="java.io.tmpdir" />
<!-- 必须要有defaultCache -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskSpoolBufferSizeMB="30"
maxElementsOnDisk="10000000"
overflowToDisk="false"
diskExpiryThreadIntervalSeconds="120">
</defaultCache>
<cache name="student"
maxElementsInMemory="100"
maxElementsOnDisk="1000"
eternal="false"
timeToIdleSeconds="5"
timeToLiveSeconds="5"
overflowToDisk="false"
memoryStoreEvictionPolicy="LFU">
</cache>
<cache name="school"
maxElementsInMemory="100"
maxElementsOnDisk="500"
eternal="false"
timeToIdleSeconds="240"
timeToLiveSeconds="240"
overflowToDisk="false"
memoryStoreEvictionPolicy="LFU">
</cache>
</ehcache>
Student.java
package com.fei.bean;
public class Student {
private String code ;
private String name;
public Student() {
}
public Student(String code, String name) {
super();
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student clone(){
return new Student(this.code,this.name);
}
}
School.java
package com.fei.bean;
//如果需要将对象缓存到磁盘,则对象需要序列化
public class School {
private String code;
private String name;
public School() {
}
public School(String code, String name) {
super();
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public School clone(){
return new School(this.code,this.name);
}
}
SchoolDao.java
package com.fei.dao;
import com.fei.bean.School;
import com.fei.database.SchoolDB;
import com.fei.util.EHcacheUtil;
public class SchoolDao {
private static final String CACHE_NAME = "school";
/**
* 先从缓存获取,缓存没有,再从数据库中拿
*/
public School get(String code){
School s = null;
s =(School) EHcacheUtil.getInstance().get(CACHE_NAME,code);
if(s == null ) {
System.out.println("缓存中找不到"+code+"的学校");
}else{
System.out.println("缓存中找到了"+code+"的学校");
return s;
}
s = SchoolDB.get(code);
//放入缓存
EHcacheUtil.getInstance().put(CACHE_NAME, code, s);
return s;
}
/**
* 更新时,删除缓存(或者也更新缓存)
*/
public void update(School s){
EHcacheUtil.getInstance().remove(CACHE_NAME, s.getCode());
SchoolDB.update(s);
}
/**
* 删除,删除缓存,删除数据库
*/
public void delete(School s){
EHcacheUtil.getInstance().remove(CACHE_NAME, s.getCode());
SchoolDB.delete(s);
}
/**
* 增加,添加到缓存,添加到数据库
*/
public void add(School s){
EHcacheUtil.getInstance().remove(CACHE_NAME, s.getCode());
SchoolDB.insert(s);
}
}
StudentDao.java
package com.fei.dao;
import com.fei.bean.Student;
import com.fei.database.StudentDB;
import com.fei.util.EHcacheUtil;
public class StudentDao {
private static final String CACHE_NAME = "student";
/**
* 先从缓存获取,缓存没有,再从数据库中拿
*/
public Student get(String code){
Student s = null;
s =(Student) EHcacheUtil.getInstance().get(CACHE_NAME,code);
if(s == null ) {
System.out.println("缓存中找不到"+code+"的学生");
}else{
System.out.println("缓存中找到了"+code+"的学生");
return s;
}
s = StudentDB.get(code);
//放入缓存
EHcacheUtil.getInstance().put(CACHE_NAME, code, s);
return s;
}
/**
* 更新时,删除缓存(或者也更新缓存)
*/
public void update(Student s){
EHcacheUtil.getInstance().remove(CACHE_NAME, s.getCode());
StudentDB.update(s);
}
/**
* 删除,删除缓存,删除数据库
*/
public void delete(Student s){
EHcacheUtil.getInstance().remove(CACHE_NAME, s.getCode());
StudentDB.delete(s);
}
/**
* 增加,添加到缓存,添加到数据库
*/
public void add(Student s){
EHcacheUtil.getInstance().remove(CACHE_NAME, s.getCode());
StudentDB.insert(s);
}
}
SchoolDB.java
package com.fei.database;
import java.util.HashMap;
import java.util.Map;
import com.fei.bean.School;
/**
* 模拟数据库的增删改查
*
*/
public class SchoolDB {
public static Map<String,School> schools = new HashMap<String , School>();
static{
schools.put("s001",new School("s001","魏国"));
schools.put("s002",new School("s002","吴国"));
schools.put("s003",new School("s003","蜀国"));
}
public static School get(String code){
School s = schools.get(code);
return s != null ? s.clone() : null;
}
public static void insert(School s){
schools.put(s.getCode(), s);
}
public static void update(School s){
School tempS = schools.get(s.getCode());
tempS.setName(s.getName());
}
public static void delete(School s){
schools.remove(s.getCode());
}
}
StudentDB.java
package com.fei.database;
import java.util.HashMap;
import java.util.Map;
import com.fei.bean.Student;
/**
* 模拟数据库的增删改查
*
*/
public class StudentDB {
public static Map<String,Student> students = new HashMap<String,Student>();
static{
students.put("0001",new Student("0001","貂蝉"));
students.put("0002",new Student("0002","赵飞燕"));
students.put("0003",new Student("0003","小乔"));
}
public static Student get(String code){
Student s = students.get(code);
return s != null ? s.clone() : null;
}
public static void insert(Student s){
students.put(s.getCode(), s);
}
public static void update(Student s){
Student tempS = students.get(s.getCode());
tempS.setName(s.getName());
}
public static void delete(Student s){
students.remove(s.getCode());
}
}
EHcacheUtil.java
package com.fei.util;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
*cacheManager:缓存管理器,以前是只允许单例的,不过现在也可以多实例了
*cache:缓存管理器内可以放置若干cache,存放数据的实质,所有cache都实现了Ehcache接口
*element:单条缓存数据的组成单位
* @author Administrator
*
*/
public class EHcacheUtil {
private static final String path = "ehcache.xml";
private static EHcacheUtil ehcacheUtil;
private CacheManager manager;
private EHcacheUtil(){
manager = CacheManager.create(EHcacheUtil.class.getResourceAsStream(path));
}
public synchronized static EHcacheUtil getInstance(){
if(ehcacheUtil == null){
return new EHcacheUtil();
}
return ehcacheUtil;
}
public void put(String cacheName, String key, Object value) {
Cache cache = getCache(cacheName);
Element element = new Element(key, value);
cache.put(element);
}
public Object get(String cacheName, String key) {
Cache cache = manager.getCache(cacheName);
Element element = cache.get(key);
return element == null ? null : element.getObjectValue();
}
public void remove(String cacheName, String key) {
Cache cache = manager.getCache(cacheName);
cache.remove(key);
}
public Cache getCache(String cacheName){
Cache cache = manager.getCache(cacheName);
if(cache == null){
throw new RuntimeException("根据cacheName="+cacheName+"无法获取到对于的cache!请检查配置文件"+path);
}
return cache;
}
}
EHcacheTest.java
package com.fei;
import net.sf.ehcache.Cache;
import com.fei.bean.School;
import com.fei.bean.Student;
import com.fei.dao.SchoolDao;
import com.fei.dao.StudentDao;
import com.fei.database.StudentDB;
import com.fei.util.EHcacheUtil;
public class EHcacheTest {
private static StudentDao studentDao = new StudentDao();
private static SchoolDao schoolDao = new SchoolDao();
public static void main(String[] args) {
// test01();
// test02();
// test03();
// test04();
}
/**
* 测试1
* 2次查询同一个对象
* 期待:第一次缓存中不存在,第二次缓存中存在
*/
private static void test01(){
studentDao.get("0001");
studentDao.get("0001");
}
/**
* 查询2次,更新对象,再查询2次,
* 期待:第一次缓存中不存在,第二次缓存中存在,第三次缓存中不存在,第四次缓存中存在
*/
private static void test02(){
schoolDao.get("s001");
School s = schoolDao.get("s001");
s.setName(s.getName()+"aaa");
schoolDao.update(s);
schoolDao.get("s001");
s = schoolDao.get("s001");
System.out.println("学校名称:"+s.getName());
}
/**
* 测试3
* 4次查询学生,第二次查询后线程休息10秒
* 期待:第一次缓存中不存在,第二次缓存中存在,第三次缓存中不存在,第四次缓存中存在
*
*/
private static void test03(){
studentDao.get("0001");
studentDao.get("0001");
try {
Thread.currentThread().sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
studentDao.get("0001");
studentDao.get("0001");
}
/**
* 测试4
* 4次查询学生
* 期待:第一次缓存中不存在,第二次缓存中存在,第三次缓存中存在,第四次缓存中存在
*/
private static void test04(){
studentDao.get("0001");
studentDao.get("0001");
studentDao.get("0001");
studentDao.get("0001");
}
}
运行test01()的结果:
缓存中找不到0001的学生
缓存中找到了0001的学生
缓存中找到了0001的学生
运行test02()的结果
缓存中找不到s001的学校
缓存中找到了s001的学校
缓存中找不到s001的学校
缓存中找到了s001的学校
学校名称:魏国aaa
缓存中找到了s001的学校
缓存中找不到s001的学校
缓存中找到了s001的学校
学校名称:魏国aaa
运行test03()的结果:
缓存中找不到0001的学生
缓存中找到了0001的学生
缓存中找不到0001的学生
缓存中找到了0001的学生
缓存中找到了0001的学生
缓存中找不到0001的学生
缓存中找到了0001的学生
运行test04()的结果:
缓存中找不到0001的学生
缓存中找到了0001的学生
缓存中找到了0001的学生
缓存中找到了0001的学生
缓存中找到了0001的学生
缓存中找到了0001的学生
缓存中找到了0001的学生