本文介绍使用EhCache实现页面缓存和对象缓存。
一、准备工作
1、本文使用Spring整合EhCache,所以保证Spring工程配置正确,可以正常运行
2、EhCache官网下载jar包,并添加到工程lib
ehcache-core-2.6.7-distribution.tar.gz (核心)
ehcache-web-2.0.4-distribution.tar.gz (页面缓存)
3、在工程src目录添加ehcache.xml配置文件
ehcache-core-2.6.7.jar中可以找到示例文件,以下是最简单的配置:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="ehcache.xsd"
updateCheck="false" monitoring="autodetect"
dynamicConfig="true">
<diskStore path="F:/icu/temp"/>
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskSpoolBufferSizeMB="30"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
statistics="false">
</defaultCache>
<cache name = "SimplePageCachingFilter"
maxEntriesLocalHeap="100"
maxElementsOnDisk="10000"
eternal="false"
overflowToDisk="true"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="120"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU">
</cache>
<cache name="objectCache"
maxEntriesLocalHeap="10000"
maxElementsOnDisk="1000000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="1800"
timeToLiveSeconds="3600"
memoryStoreEvictionPolicy="LFU" />
</ehcache>
二、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();
页面缓存主要用Filter过滤器对请求的url进行过滤,如果该url在缓存中出现。那么页面数据就从缓存对象中获取,并以gzip压缩后返回。其速度是没有压缩缓存时速度的3-5倍,
效率相当之高!其中页面缓存的过滤器有CachingFilter,一般要扩展filter或是自定义Filter都继承该CachingFilter。
CachingFilter功能可以对HTTP响应的内容进行缓存。这种方式缓存数据的粒度比较粗,例如缓存整张页面。它的优点是使用简单、效率高,缺点是不够灵活,可重用程度不
高。
EHCache使用SimplePageCachingFilter类实现Filter缓存。该类继承自CachingFilter,有默认产生cache key的calculateKey()方法,该方法使用HTTP请求的URI和查询条件来
组成key。也可以自己实现一个Filter,同样继承CachingFilter类,然后覆写calculateKey()方法,生成自定义的key。
CachingFilter输出的数据会根据浏览器发送的Accept-Encoding头信息进行Gzip压缩。
在使用Gzip压缩时,需注意两个问题:
1) Filter在进行Gzip压缩时,采用系统默认编码,对于使用GBK编码的中文网页来说,需要将操作系统的语言设置为:zh_CN.GBK,否则会出现乱码的问题。
2) 默认情况下CachingFilter会根据浏览器发送的请求头部所包含的Accept-Encoding参数值来判断是否进行Gzip压缩。虽然IE6/7浏览器是支持Gzip压缩的,但是在发送请求的
时候却不带该参数。为了对IE6/7也能进行Gzip压缩,可以通过继承CachingFilter,实现自己的Filter,然后在具体的实现中覆写方法acceptsGzipEncoding。
具体代码:
import java.util.Enumeration;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
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;
/**
* 页面缓存过滤器
*/
public class EhCachePageFilter extends SimplePageCachingFilter {
private final static Logger log = Logger.getLogger(EhCachePageFilter.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("rawtypes")
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;
}
/**
* @see net.sf.ehcache.constructs.web.filter.Filter#acceptsGzipEncoding(javax.servlet.http.HttpServletRequest)
* <b>function:</b> 兼容ie6/7 gzip压缩
*/
@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;
}
} 在web.xml中添加过滤器配置:
<!-- 配置EhCache Page Cache -->
<filter>
<filter-name>EhCachePageFilter</filter-name>
<filter-class>cn.zicheng.ehcache.filter.EhCachePageFilter</filter-class>
<init-param>
<param-name>patterns</param-name>
<!-- 配置你需要缓存的url -->
<param-value>/cache.jsp, product.action, market.action</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EhCachePageFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>EhCachePageFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping> 当第一次请求这些页面后,这些页面就会被添加到缓存中,以后请求这些页面将会从缓存中获取。你可以在cache.jsp页面中用小脚本来测试该页面是否被缓存。<%=new
Date()%>如果时间是变动的,则表示该页面没有被缓存或是缓存已经过期,否则则是在缓存状态了。
四、对象缓存
对象缓存就是将查询的数据,添加到缓存中,下次再次查询的时候直接从缓存中获取,而不去数据库中查询。
1、对象缓存一般是针对方法、类而来的,结合Spring的Aop对象、方法缓存就很简单。这里需要用到切面编程,用到了Spring的MethodInterceptor或是用@Aspect。
代码如下:
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;
import org.springframework.util.Assert;
/**
* <b>function:</b> 缓存方法拦截器核心代码
*/
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 {
Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it.");
}
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();
}
/**
* <b>function:</b> 返回具体的方法全路径名称 参数
* @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中是否存在。如果存在就从缓存中取出该
对象,转换成我们要的返回类型。没有的话就把该方法返回的对象添加到缓存中即可。值得主意的是当前方法的参数和返回值的对象类型需要序列化。
2、随后,再建立一个拦截器MethodCacheAfterAdvice,作用是在用户进行create/update/delete操作时来刷新相关cache内容,这个拦截器实现了AfterReturningAdvice接口,
将会在所拦截的方法执行后执行在public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3)方法中所预定的操作。
import java.lang.reflect.Method;
import java.util.List;
import net.sf.ehcache.Cache;
import org.apache.log4j.Logger;
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 Logger logger = Logger.getLogger(MethodCacheAfterAdvice.class);
private Cache cache;
public void setCache(Cache cache) {
this.cache = cache;
}
public MethodCacheAfterAdvice() {
super();
}
@Override
public void afterReturning(Object arg0, Method arg1, Object[] arg2, 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.debug("remove cache " + cacheKey);
}
}
}
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache, "Need a cache. Please use setCache(Cache) create it.");
}
} 上面的代码很简单,实现了afterReturning方法实现自AfterReturningAdvice接口,方法中所定义的内容将会在目标方法执行后执行,在该方法中
String className = arg3.getClass().getName();
获取目标class的全名,如:cn.zicheng.icu.service.UserService,然后循环cache的key list,remove cache中所有和该class相关的element。
3、然后,在将Cache和两个拦截器配置到Spring,这里没有使用AOP的标签。在src目录下applicationContext.xml完成配置,该配置主意是注入我们的cache对象,哪个
cache来管理对象缓存,然后哪些类、方法参与该拦截器的扫描。
<!-- 配置eh缓存管理器 -->
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcache.xml</value>
</property>
</bean>
<!-- 配置一个简单的缓存工厂bean对象 -->
<bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager" ref="cacheManager" />
<!-- 使用缓存 关联ehcache.xml中的缓存配置 -->
<property name="cacheName" value="objectCache" />
</bean>
<!-- 配置一个缓存拦截器对象,处理具体的缓存业务 -->
<bean id="methodCacheInterceptor" class="cn.zicheng.ehcache.aop.MethodCacheInterceptor">
<property name="cache" ref="ehCache"/>
</bean>
<!-- 配置一个缓存拦截器对象,create/update/delete操作时来刷新相关cache内容 -->
<bean id="methodCacheAfterAdvice" class="cn.zicheng.ehcache.aop.MethodCacheAfterAdvice">
<property name="cache" ref="ehCache" />
</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>get.+</value>
<value>search.+</value>
<value>find.+</value>
</list>
</property>
</bean>
<!-- 刷新缓存的切入点对象 -->
<bean id="methodCachePointCutAdvice" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice" ref="methodCacheAfterAdvice"/>
<property name="patterns">
<list>
<value>create.+</value>
<value>add.+</value>
<value>update.+</value>
<value>delete.+</value>
<value>del.+</value>
</list>
</property>
</bean> 4、使用代理的方式,对需要缓存的Service进行AOP配置
<bean id="userServiceTarget" class="cn.zicheng.icu.service.impl.UserService"></bean>
<bean id="userService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target">
<ref local="userServiceTarget"/>
</property>
<property name="interceptorNames">
<list>
<value>methodCacheInterceptor</value>
<value>methodCachePointCutAdvice</value>
</list>
</property>
</bean> 5、在userService中编写操作数据库的方法,然后在浏览器中访问调用userService的action。从日志中可以看出,第一次有对数据库进行了操作,有SQL打印出来;第二次不再操作数据库,直接从缓存中取出结果,没有打印SQL日志。
参考:
http://raychase.iteye.com/blog/1545906
http://tom-duan.iteye.com/blog/99721
http://www.cnblogs.com/hoojo/archive/2012/07/12/2587556.html

本文详细介绍如何使用EhCache实现页面缓存和对象缓存。包括EhCache的基本用法、页面缓存的具体实现及对象缓存的应用场景。通过Spring AOP实现方法级别的缓存,并在特定操作时刷新缓存。
631

被折叠的 条评论
为什么被折叠?



