一、Ehcache缓存框架工作原理
????Ehcache没有提供在web.xml加载的接口,所以必需将Ehchahe的配置文件放到class目录下(web容器在启动的时候会自动加载class目录下的所有文件),在项目启动后Ehchate会自动读取ehchahe.xml配置文件。
??? 添加了缓存,当数据有改动的时候,需要清除缓存,如有对数据做增加和修改的时候需要清除相关联的缓存。
?
二、mybatis+Ehcache简单实现缓存需要的jar包:
??? ehcache-core-2.4.4.jar
??? slf4j-api-1.6.1.jar
??? slf4j-log4j12-1.6.2.jar
??? mybatis-ehcache-1.0.0.jar(需不需要还么没确定)
?
三、例子
??? 1、Ehcache配置文件“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" updateCheck="false"> <diskStore path="java.io.tmpdir" /> <!-- 默认缓存配置 --> <defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="0" timeToLiveSeconds="600" overflowToDisk="false" diskPersistent="false" memoryStoreEvictionPolicy="LRU" /> <!-- 自定义,service缓存配置 eternal: 缓存是否永远不销毁 maxElementsInMemory: 缓存可以存储的总记录量 overflowToDisk: 当缓存中的数据达到最大值时,是否把缓存数据写入磁盘 diskPersistent: 是否启用强制命令将缓存出入磁盘 timeToIdleSeconds: 当缓存闲置时间超过该值,则缓存自动销毁,如果该值是0就意味着元素可以停顿无穷长的时间 timeToLiveSeconds: 缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值, 这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间 memoryStoreEvictionPolicy: 缓存满了之后的淘汰算法 --> <cache name="serviceCache" eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LRU" /> </ehcache>
?
?
??? 2、缓存父类管理类“EhCacheManager.java”
package com.util;
import java.io.Serializable;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 缓存管理类
*/
public class EhCacheManager {
private static Log log = LogFactory.getLog(EhCacheManager.class);
private static final String CACHE_KEY = "serviceCache";
public static final int CACHE_LIVE_SECONDS = 180;
private static EhCacheManager instance = new EhCacheManager();
private static CacheManager cacheManager;
private static Ehcache fileCache;
private EhCacheManager() {
log.info("Init file cache ----------------------------------------");
cacheManager = new CacheManager();
fileCache = cacheManager.getCache(CACHE_KEY);
log.info("Init file cache success....");
}
public static synchronized EhCacheManager getInstance() {
if (instance == null) {
instance = new EhCacheManager();
}
return instance;
}
public static byte[] loadFile(String key) {
Element e = fileCache.get(key);
if (e != null) {
Serializable s = e.getValue();
if (s != null) {
return (byte[]) s;
}
}
return null;
}
public static void cacheFile(String key, byte[] data) {
fileCache.put(new Element(key, data));
}
/**
* 将数据存入缓存,缓存无时间限制
* @param key
* @param value
*/
public static <T> void put(String key,T value){
fileCache.put(new Element(key, value));
}
/**
* 带过期时间的缓存,存入
* @param key 键
* @param value 值
* @param timeToLiveSeconds 缓存过期时间
*/
public static <T> void put(String key,T value,int timeToLiveSeconds){
fileCache.put(new Element(key, value,0,timeToLiveSeconds));
}
/**
* 通过key值获取存入缓存中的数据
* @param key 数据存入缓存时的key
*/
@SuppressWarnings("unchecked")
public static <T> T get(String key) {
Element el = fileCache.get(key);
if (el == null) {
if (log.isDebugEnabled())
log.debug("not found key: " + key);
return null;
}
T t = (T) el.getObjectValue();
return t;
}
/**
* 根据key删除缓存
*/
public static boolean remove(String key) {
log.info("remove key:"+key);
return fileCache.remove(key);
}
public static void shutdown() {
cacheManager.shutdown();
}
}
? ?
??? 3、使用了缓存的类"UserServiceImpl.java"
package com.service.impl;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.dao.UserDao;
import com.entity.User;
import com.service.UserService;
import com.util.EhCacheManager;
/**
* 用户管理service实现类
*/
@Service(value="userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
private final static String GET_USER_KEY = "GET_USER_KEY_";
/**
* 增加或修改用户
*/
public int userOperate(User user){
if(user.getId() == null){
return userDao.addUser(user);
}else{
return userDao.updateUser(user);
}
}
/**
* 删除用户
*/
public int deleteUser(String id){
return userDao.deleteUser(id);
}
/**
* 用户登录,从缓存中取数据,如果没有就查数据库
*/
public List<User> getUserDenglu(Map<String,Object> params){
List<User> listUser = EhCacheManager.get(GET_USER_KEY+params.get("account")+"_"+params.get("password"));
if(listUser == null){
listUser = userDao.getUserDenglu(params);
EhCacheManager.put(GET_USER_KEY+params.get("account")+"_"+params.get("password"), listUser);
}
return listUser;
}
/**
* 查询用户
*/
public List<User> getUser(Map<String,Object> params){
return userDao.getUser(params);
}
/**
* 查询用户总数
*/
public int getUserCount(Map<String,Object> params){
return userDao.getUserCount(params);
}
}
?
??? 4、删除缓存
??? EhCacheManager.remove(GET_USER_KEY+params.get("account")+"_"+params.get("password"));
???
??? 所需jar包如附件: