Ehcache也可以做分布是缓存,分布是缓存参考地址:
http://www.cnblogs.com/yangy608/archive/2011/10/07/2200669.html
一、Ehcache缓存框架工作原理
将ehcache-core-2.4.8.jar加入到项目中后,web项目启动后Ehcache就会启动(没有提供在web.xml启动加载的接口)。
添加了缓存,当数据有改动的时候,需要清除缓存,如有对数据做增加和修改的时候需要清除相关联的缓存。
CacheManager 在使用之后应该关闭,虽然有自己的 shutdown hook ,建议在程序中手动关闭。
CacheManager.getInstance().shutdown();
二、CacheManager对象的创建方式
1、无参
CacheManager manager = new CacheManager();
说明:Ehcache在启动的时候会扫描classes目录下的ehcache.xml配置文件,创建CacheManager对象,如果将ehcache.xml文件放到classes目录下,可以通过无参形式加载配置文件;
2、通过配置文件
CacheManager manager = new CacheManager("E:\tomcat.6.0.37\webapps\easyUiPowerManage\WEB-INF\ehcache.xml");
说明:如果没有将配置文件放在classes目录下,则在ehcache启动的时候找不到配置文件,没有创建CacheManager对象,所以在加载配置文件的时候需要通过路径来加载配置文件;
3、通过资源
URL url = getClass().getResource("/anotherconfigurationname.xml");
CacheManager manager = new CacheManager(url);
4、通过输入流
InputStream fis = new FileInputStream(new File("src/config/ehcache.xml").getAbsolutePath());
try {
CacheManager manager = new CacheManager(fis);
} finally {
fis.close();
}
三、mybatis+Ehcache简单实现缓存需要的jar包:
ehcache-core-2.4.8.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.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);
}
/**
* 关闭cacheManager 对象
*/
public static void shutdown() {
cacheManager.shutdown();
}
}
3、使用了缓存的类"UserServiceImpl.java"
package com.service.impl;
import java.util.HashMap;
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) {
Map<String,Object> params = new HashMap<String, Object>();
params.put("id",id);
//根据id查询用户
List<User> listUser = userDao.getUser(params);
//删除之前登录保存的缓存
if(listUser.size() > 0){
User user = listUser.get(0);
EhCacheManager.remove(GET_USER_KEY+user.getAccount()+"_"+user.getPassword());
}
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"));