一准备的工作
1.已经整合了spring、hibernte的项目
2.把 ehcache-core-2.4.5 ehcache-web-2.0.3 两个jar包添加到lib下
3 把相关文件: ehcache.xsd ehcache.xml 两个文件添加到 src下
二 ehcache常用方法
CacheManager cacheManager = CacheManager.create();
// 或者
cacheManager = CacheManager.getInstance();
// 或者
cacheManager = CacheManager.create("/config/ehcache.xml");
// 或者
cacheManager = CacheManager.create(" http://localhost:8080/test/ehcache.xml");
cacheManager = CacheManager.newInstance("/config/ehcache.xml");
// .......
// 获取ehcache配置文件中的一个cache
Cache sample = cacheManager.getCache("sample");
// 获取页面缓存
BlockingCache cache = new BlockingCache(cacheManager.getEhcache("SimplePageCachingFilter"));
// 添加数据到缓存中
Element element = new Element("key", "val");
sample.put(element);
// 获取缓存中的对象,注意添加到cache中对象要序列化 实现Serializable接口
Element result = sample.get("key");
// 删除缓存
sample.remove("key");
sample.removeAll();
// 获取缓存管理器中的缓存配置名称
for (String cacheName : cacheManager.getCacheNames()) {
System.out.println(cacheName);
}
// 获取所有的缓存对象
for (Object key : cache.getKeys()) {
System.out.println(key);
}
// 得到缓存中的对象数
cache.getSize();
// 得到缓存对象占用内存的大小
cache.getMemoryStoreSize();
// 得到缓存读取的命中次数
cache.getStatistics().getCacheHits();
// 得到缓存读取的错失次数
cache.getStatistics().getCacheMisses();
// 或者
cacheManager = CacheManager.getInstance();
// 或者
cacheManager = CacheManager.create("/config/ehcache.xml");
// 或者
cacheManager = CacheManager.create(" http://localhost:8080/test/ehcache.xml");
cacheManager = CacheManager.newInstance("/config/ehcache.xml");
// .......
// 获取ehcache配置文件中的一个cache
Cache sample = cacheManager.getCache("sample");
// 获取页面缓存
BlockingCache cache = new BlockingCache(cacheManager.getEhcache("SimplePageCachingFilter"));
// 添加数据到缓存中
Element element = new Element("key", "val");
sample.put(element);
// 获取缓存中的对象,注意添加到cache中对象要序列化 实现Serializable接口
Element result = sample.get("key");
// 删除缓存
sample.remove("key");
sample.removeAll();
// 获取缓存管理器中的缓存配置名称
for (String cacheName : cacheManager.getCacheNames()) {
System.out.println(cacheName);
}
// 获取所有的缓存对象
for (Object key : cache.getKeys()) {
System.out.println(key);
}
// 得到缓存中的对象数
cache.getSize();
// 得到缓存对象占用内存的大小
cache.getMemoryStoreSize();
// 得到缓存读取的命中次数
cache.getStatistics().getCacheHits();
// 得到缓存读取的错失次数
cache.getStatistics().getCacheMisses();
三 页面缓存的用法
页面缓存主要用Filter过滤器对请求的url进行过滤,如果该url在缓存中出现。那么页面数据就从缓存对象中获取,并以gzip压缩后返回。一般要扩展filter或是自定义Filter继承SimplePageCachingFilter。这种方式缓存数据的粒度比较粗,例如缓存整张页面。它的优点是使用简单、效率高,缺点是不够灵活,可重用程度不高。对于常时间无变化的首页可参考用一下。
在<ehcache></ehcache>之间加入如下配置
<!-- 配置自定义缓存 maxElementsInMemory:缓存中允许创建的最大对象数 eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。 timeToIdleSeconds:闲置时间,单位为秒,如果该值是 0 就意味着元素可以停顿无穷长的时间。 timeToLiveSeconds:缓存数据的生存时间,如果该值是0就意味着元素可以停顿无穷长的时间。 overflowToDisk:内存不足时,是否启用磁盘缓存。 memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。 --> <cache name="SimplePageCachingFilter" maxElementsInMemory="10000" eternal="false" overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="120" memoryStoreEvictionPolicy="LFU" />
具体的java代码
import java.util.Enumeration;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.constructs.blocking.LockTimeoutException;
import net.sf.ehcache.constructs.web.AlreadyCommittedException;
import net.sf.ehcache.constructs.web.AlreadyGzippedException;
import net.sf.ehcache.constructs.web.filter.FilterNonReentrantException;
import net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
/****
* 页面缓存过滤器
* @author Administrator
*
*/
public class PageEhCacheFilter extends SimplePageCachingFilter{
private final static Logger log = Logger.getLogger(PageEhCacheFilter.class);
private final static String FILTER_URL_PATTERNS = "patterns";
private static String[] cacheURLs;
private void init() throws CacheException {
String patterns = filterConfig.getInitParameter(FILTER_URL_PATTERNS);
cacheURLs = StringUtils.split(patterns, ",");
}
@Override
protected void doFilter(final HttpServletRequest request,
final HttpServletResponse response, final FilterChain chain)
throws AlreadyGzippedException, AlreadyCommittedException,
FilterNonReentrantException, LockTimeoutException, Exception {
if (cacheURLs == null) {
init();
}
String url = request.getRequestURI();
boolean flag = false;
if (cacheURLs != null && cacheURLs.length > 0) {
for (String cacheURL : cacheURLs) {
if (url.contains(cacheURL.trim())) {
flag = true;
break;
}
}
}
// 如果包含我们要缓存的url 就缓存该页面,否则执行正常的页面转向
if (flag) {
String query = request.getQueryString();
if (query != null) {
query = "?" + query;
}
log.info("当前请求已缓存:" + url + query);
super.doFilter(request, response, chain);
} else {
chain.doFilter(request, response);
}
}
@SuppressWarnings("unchecked")
private boolean headerContains(final HttpServletRequest request, final String header, final String value) {
logRequestHeaders(request);
final Enumeration accepted = request.getHeaders(header);
while (accepted.hasMoreElements()) {
final String headerValue = (String) accepted.nextElement();
if (headerValue.indexOf(value) != -1) {
return true;
}
}
return false;
}
@Override
protected boolean acceptsGzipEncoding(HttpServletRequest request) {
boolean ie6 = headerContains(request, "User-Agent", "MSIE 6.0");
boolean ie7 = headerContains(request, "User-Agent", "MSIE 7.0");
return acceptsEncoding(request, "gzip") || ie6 || ie7;
}
}
使用SimplePageCachingFilter需要在web.xml中配置cacheName,cacheName默认是SimplePageCachingFilter,对应ehcache.xml中的cache配置。
在web.xml中加入如下配置,注意如果web.xml里有其他的filter的话应该在其他filter之前插入如下配置,否则可能会触发不了
<filter> <filter-name>PageEhCacheFilter</filter-name> <filter-class>com.lql.ehcache.filter.PageEhCacheFilter</filter-class> <init-param> <param-name>patterns</param-name> <!-- 配置你需要缓存的url --> <param-value>/cache.jsp,dispPersonScore.action</param-value> </init-param> </filter> <filter-mapping> <filter-name>PageEhCacheFilter</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <filter-mapping> <filter-name>PageEhCacheFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping>
四 对象缓存
对象缓存就是将查询的数据,添加到缓存中,下次再次查询的时候直接从缓存中获取,而不去数据库中查询。建议用在不常改变的数量当中如字典、省市之类,否则使用的意义不太。
对象缓存一般是针对方法、类而来的,结合Spring的Aop对象、方法缓存就很简单。这里需要用到切面编程,用到了Spring的MethodInterceptor或是用@Aspect。
具体java代码
import java.io.Serializable;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
public class MethodCacheInterceptor implements MethodInterceptor,
InitializingBean {
private static final Logger log = Logger
.getLogger(MethodCacheInterceptor.class);
private Cache cache;
public void setCache(Cache cache) {
this.cache = cache;
}
public void afterPropertiesSet() throws Exception {
log.info(cache
+ " A cache is required. Use setCache(Cache) to provide one.");
}
/****
* 拦截后执行的代码段
*/
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
String targetName = invocation.getThis().getClass().getName();
String methodName = invocation.getMethod().getName();
Object[] arguments = invocation.getArguments();
Object result;
String cacheKey = getCacheKey(targetName, methodName, arguments);
Element element = null;
synchronized (this) {
element = cache.get(cacheKey);
if (element == null) {
log.info(cacheKey + "加入到缓存: " + cache.getName());
// 调用实际的方法
result = invocation.proceed();
element = new Element(cacheKey, (Serializable) result);
cache.put(element);
} else {
log.info(cacheKey + "使用缓存: " + cache.getName());
}
}
return element.getValue();
}
/**
* 返回具体的方法全路径名称 参数
@param targetName 全路径
* @param methodName 方法名称
* @param arguments 参数
* @return 完整方法名称
*/
private String getCacheKey(String targetName, String methodName,
Object[] arguments) {
StringBuffer sb = new StringBuffer();
sb.append(targetName).append(".").append(methodName);
if ((arguments != null) && (arguments.length != 0)) {
for (int i = 0; i < arguments.length; i++) {
sb.append(".").append(arguments[i]);
}
}
return sb.toString();
}
}
这个方法拦截器主要是对你要拦截的类的方法进行拦截,然后判断该方法的类路径+方法名称+参数值组合的cache key在缓存cache中是否存在。如果存在就从缓存中取出该对象,转换成我们要的返回类型。没有的话就把该方法返回的对象添加到缓存中即可。值得主意的是当前方法的参数和返回值的对象类型需要序列化。还有就是配置拦截的方法的正则表达式时,注意继承类的父类中的方法不能被拦截,如果需要要改为拦截父类。或者是在子类中重写父类的方法。
在spring的配置文件中添加的配置如下
<!-- 配置eh缓存管理器 --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/> <!-- 配置一个简单的缓存工厂bean对象 --> <bean id="simpleCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager" ref="cacheManager" /> <!-- 使用缓存 关联ehcache.xml中的缓存配置 --> <property name="cacheName" value="objCache" /> </bean> <!-- 配置一个缓存拦截器对象,处理具体的缓存业务 --> <bean id="methodCacheInterceptor" class="com.lql.ehcache.filter.MethodCacheInterceptor"> <property name="cache"><ref local="simpleCache" /></property> </bean> <!-- 这里配置需要进行缓存的类方法 --> <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <!-- 配置缓存aop切面 --> <property name="advice" ref="methodCacheInterceptor" /> <!-- 配置哪些方法参与缓存策略 --> <!-- .表示符合任何单一字元 ### +表示符合前一个字元一次或多次 ### *表示符合前一个字元零次或多次 ### \Escape任何Regular expression使用到的符号 --> <!-- .*表示前面的前缀(包括包名) 表示print方法--> <property name="patterns"> <list> <value>com.lql.comon.service.CommonModelMaintain.findById.*</value> </list> </property> </bean>
在ehcache.xml中添加如下cache配置
<cache name="objCache" maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="1800" timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU" />
五 扩展学习
如果系统运行中缓存的数据发生改变了,那是干等着它消亡么这显然不符合我们的要求。这时我们可以使用spriing 的通知
AfterReturningAdvice,执行完某个方法后执行的操作。
具体代码
import java.lang.reflect.Method;
import java.util.List;
import net.sf.ehcache.Cache;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
public class MethodCacheAfterAdvice implements AfterReturningAdvice,
InitializingBean {
private static final Log logger = LogFactory
.getLog(MethodCacheAfterAdvice.class);
private Cache cache;
public void setCache(Cache cache) {
this.cache = cache;
}
public MethodCacheAfterAdvice() {
super();
}
public void afterReturning(Object arg0, Method method, Object[] arguments,
Object arg3) throws Throwable {
String className = arg3.getClass().getName();
List list = cache.getKeys();
for (int i = 0; i < list.size(); i++) {
String cacheKey = String.valueOf(list.get(i));
if (cacheKey.startsWith(className)) {
cache.remove(cacheKey);
logger.info("删除缓存 " + cacheKey);
}
}
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache,
"Need a cache. Please use setCache(Cache) create it.");
}
在spring文件中加入下面配置
<!-- 配置一个缓存内容更改通知,处理具体的缓存内容更改后业务 --> <bean id="methodCacheAfterAdvice" class="com.lql.ehcache.filter.MethodCacheAfterAdvice"> <property name="cache"><ref local="simpleCache" /></property> </bean> <!-- 这里配置需要进行缓存内容更改侦听的类方法 --> <bean id="methodAfterPointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <!-- 配置缓存aop切面 --> <property name="advice" ref="methodCacheAfterAdvice" /> <property name="patterns"> <list> <value>com.lql.comon.service.CommonModelMaintain.remove.*</value> <value>com.lql.comon.service.CommonModelMaintain.saveOrUpdate.*</value> </list> </property> </bean>