'target='_blank'>http://blog.csdn.net/IBM_hoojo
*@emailhoojo_@126.com
*@version1.0
*/
publicclassPageEhCacheFilterextendsSimplePageCachingFilter{
privatefinalstaticLoggerlog=Logger.getLogger(PageEhCacheFilter.class);
privatefinalstaticStringFILTER_URL_PATTERNS="patterns";
privatestaticString[]cacheURLs;
privatevoidinit()throwsCacheException{
Stringpatterns=filterConfig.getInitParameter(FILTER_URL_PATTERNS);
cacheURLs=StringUtils.split(patterns,",");
}
@Override
protectedvoiddoFilter(finalHttpServletRequestrequest,
finalHttpServletResponseresponse,finalFilterChainchain)
throwsAlreadyGzippedException,AlreadyCommittedException,
FilterNonReentrantException,LockTimeoutException,Exception{
if(cacheURLs==null){
init();
}
Stringurl=request.getRequestURI();
booleanflag=false;
if(cacheURLs!=null&&cacheURLs.length>0){
for(StringcacheURL:cacheURLs){
if(url.contains(cacheURL.trim())){
flag=true;
break;
}
}
}
//如果包含我们要缓存的url就缓存该页面,否则执行正常的页面转向
if(flag){
Stringquery=request.getQueryString();
if(query!=null){
query="?"+query;
}
log.info("当前请求被缓存:"+url+query);
super.doFilter(request,response,chain);
}else{
chain.doFilter(request,response);
}
}
@SuppressWarnings("unchecked")
privatebooleanheaderContains(finalHttpServletRequestrequest,finalStringheader,finalStringvalue){
logRequestHeaders(request);
finalEnumerationaccepted=request.getHeaders(header);
while(accepted.hasMoreElements()){
finalStringheaderValue=(String)accepted.nextElement();
if(headerValue.indexOf(value)!=-1){
returntrue;
}
}
returnfalse;
}
/**
*@seenet.sf.ehcache.constructs.web.filter.Filter#acceptsGzipEncoding(javax.servlet.http.HttpServletRequest)
*<b>function:</b>兼容ie6/7gzip压缩
*@authorhoojo
*@createDate2012-7-4上午11:07:11
*/
@Override
protectedbooleanacceptsGzipEncoding(HttpServletRequestrequest){
booleanie6=headerContains(request,"User-Agent","MSIE6.0");
booleanie7=headerContains(request,"User-Agent","MSIE7.0");
returnacceptsEncoding(request,"gzip")||ie6||ie7;
}
}
[/code]
这里的PageEhCacheFilter继承了SimplePageCachingFilter,一般情况下SimplePageCachingFilter就够用了,这里是为了满足当前系统需求才做了覆盖操作。使用SimplePageCachingFilter需要在web.xml中配置cacheName,cacheName默认是SimplePageCachingFilter,对应ehcache.xml中的cache配置。
在web.xml中加入如下配置
[code]<!--缓存、gzip压缩核心过滤器-->
<filter>
<filter-name>PageEhCacheFilter</filter-name>
<filter-class>com.hoo.ehcache.filter.PageEhCacheFilter</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>PageEhCacheFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>PageEhCacheFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
[/code]
当第一次请求这些页面后,这些页面就会被添加到缓存中,以后请求这些页面将会从缓存中获取。你可以在cache.jsp页面中用小脚本来测试该页面是否被缓存。<%=newDate()%>如果时间是变动的,则表示该页面没有被缓存或是缓存已经过期,否则则是在缓存状态了。
四、对象缓存
对象缓存就是将查询的数据,添加到缓存中,下次再次查询的时候直接从缓存中获取,而不去数据库中查询。
对象缓存一般是针对方法、类而来的,结合Spring的Aop对象、方法缓存就很简单。这里需要用到切面编程,用到了Spring的MethodInterceptor或是用@Aspect。
代码如下:
[code]packagecom.hoo.common.ehcache;
importjava.io.Serializable;
importnet.sf.ehcache.Cache;
importnet.sf.ehcache.Element;
importorg.aopalliance.intercept.MethodInterceptor;
importorg.aopalliance.intercept.MethodInvocation;
importorg.apache.log4j.Logger;
importorg.springframework.beans.factory.InitializingBean;
/**
*<b>function:</b>缓存方法拦截器核心代码
*@authorhoojo
*@createDate2012-7-2下午06:05:34
*@fileMethodCacheInterceptor.java
*@packagecom.hoo.common.ehcache
*@projectEhcache
*@blog'target='_blank'>http://blog.csdn.net/IBM_hoojo
*@emailhoojo_@126.com
*@version1.0
*/
publicclassMethodCacheInterceptorimplementsMethodInterceptor,InitializingBean{
privatestaticfinalLoggerlog=Logger.getLogger(MethodCacheInterceptor.class);
privateCachecache;
publicvoidsetCache(Cachecache){
this.cache=cache;
}
publicvoidafterPropertiesSet()throwsException{
log.info(cache+"Acacheisrequired.UsesetCache(Cache)toprovideone.");
}
publicObjectinvoke(MethodInvocationinvocation)throwsThrowable{
StringtargetName=invocation.getThis().getClass().getName();
StringmethodName=invocation.getMethod().getName();
Object[]arguments=invocation.getArguments();
Objectresult;
StringcacheKey=getCacheKey(targetName,methodName,arguments);
Elementelement=null;
synchronized(this){
element=cache.get(cacheKey);
if(element==null){
log.info(cacheKey+"加入到缓存:"+cache.getName());
//调用实际的方法
result=invocation.proceed();
element=newElement(cacheKey,(Serializable)result);
cache.put(element);
}else{
log.info(cacheKey+"使用缓存:"+cache.getName());
}
}
returnelement.getValue();
}
/**
*<b>function:</b>返回具体的方法全路径名称参数
*@authorhoojo
*@createDate2012-7-2下午06:12:39
*@paramtargetName全路径
*@parammethodName方法名称
*@paramarguments参数
*@return完整方法名称
*/
privateStringgetCacheKey(StringtargetName,StringmethodName,Object[]arguments){
StringBuffersb=newStringBuffer();
sb.append(targetName).append(".").append(methodName);
if((arguments!=null)&&(arguments.length!=0)){
for(inti=0;i<arguments.length;i++){
sb.append(".").append(arguments[i]);
}
}
returnsb.toString();
}
}
[/code]
这里的方法拦截器主要是对你要拦截的类的方法进行拦截,然后判断该方法的类路径+方法名称+参数值组合的cachekey在缓存cache中是否存在。如果存在就从缓存中取出该对象,转换成我们要的返回类型。没有的话就把该方法返回的对象添加到缓存中即可。值得主意的是当前方法的参数和返回值的对象类型需要序列化。
我们需要在src目录下添加applicationContext.xml完成对MethodCacheInterceptor拦截器的配置,该配置主意是注入我们的cache对象,哪个cache来管理对象缓存,然后哪些类、方法参与该拦截器的扫描。
添加配置如下:
[code]<context:component-scanbase-package="com.hoo.common.interceptor"/>
<!--配置eh缓存管理器-->
<beanid="cacheManager"class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/>
<!--配置一个简单的缓存工厂bean对象-->
<beanid="simpleCache"class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<propertyname="cacheManager"ref="cacheManager"/>
<!--使用缓存关联ehcache.xml中的缓存配置-->
<propertyname="cacheName"value="mobileCache"/>
</bean>
<!--配置一个缓存拦截器对象,处理具体的缓存业务-->
<beanid="methodCacheInterceptor"class="com.hoo.common.interceptor.MethodCacheInterceptor">
<propertyname="cache"ref="simpleCache"/>
</bean>
<!--参与缓存的切入点对象(切入点对象,确定何时何地调用拦截器)-->
<beanid="methodCachePointCut"class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<!--配置缓存aop切面-->
<propertyname="advice"ref="methodCacheInterceptor"/>
<!--配置哪些方法参与缓存策略-->
<!--
.表示符合任何单一字元
###+表示符合前一个字元一次或多次
###*表示符合前一个字元零次或多次
###\Escape任何Regularexpression使用到的符号
-->
<!--.*表示前面的前缀(包括包名)表示print方法-->
<propertyname="patterns">
<list>
<value>com.hoo.rest.*RestService*\.*get.*</value>
<value>com.hoo.rest.*RestService*\.*search.*</value>
</list>
</property>
</bean>
[/code]
在ehcache.xml中添加如下cache配置
[code]<cachename="mobileCache"
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="1800"
timeToLiveSeconds="3600"
memoryStoreEvictionPolicy="LFU"/>
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理