Ehcache 整合Spring 使用页面、对象缓存(转)

Ehcache 整合Spring 使用页面、对象缓存

Ehcache在很多项目中都出现过,用法也比较简单。一般的加些配置就可以了,而且Ehcache可以对页面、对象、数据进行缓存,同时支持集群/分布式缓存。如果整合Spring、Hibernate也非常的简单,Spring对Ehcache的支持也非常好。EHCache支持内存和磁盘的缓存,支持LRU、LFU和FIFO多种淘汰算法,支持分布式的Cache,可以作为Hibernate的缓存插件。同时它也能提供基于Filter的Cache,该Filter可以缓存响应的内容并采用Gzip压缩提高响应速度。

Email:hoojo_@126.com

Blog:http://blog.csdn.net/IBM_hoojo

http://hoojo.cnblogs.com/

一、准备工作

如果你的系统中已经成功加入Spring、Hibernate;那么你就可以进入下面Ehcache的准备工作。

1、 下载jar包

Ehcache 对象、数据缓存:http://ehcache.org/downloads/destination?name=ehcache-core-2.5.2-distribution.tar.gz&bucket=tcdistributions&file=ehcache-core-2.5.2-distribution.tar.gz

Web页面缓存:http://ehcache.org/downloads/destination?name=ehcache-web-2.0.4-distribution.tar.gz&bucket=tcdistributions&file=ehcache-web-2.0.4-distribution.tar.gz

2、 需要添加如下jar包到lib目录下

ehcache-core-2.5.2.jar

ehcache-web-2.0.4.jar 主要针对页面缓存

3、 当前工程的src目录中加入配置文件

ehcache.xml

ehcache.xsd

这些配置文件在ehcache-core这个jar包中可以找到

二、Ehcache基本用法

1CacheManager cacheManager = CacheManager.create(); 2 3// 或者 4 5cacheManager = CacheManager.getInstance(); 6 7// 或者 8 9cacheManager = CacheManager.create("/config/ehcache.xml"); 10 11// 或者 12 13cacheManager = CacheManager.create("http://localhost:8080/test/ehcache.xml"); 14 15cacheManager = CacheManager.newInstance("/config/ehcache.xml"); 16 17// ....... 18 19// 获取ehcache配置文件中的一个cache 20 21Cache sample = cacheManager.getCache("sample"); 22 23// 获取页面缓存 24 25BlockingCache cache = new BlockingCache(cacheManager.getEhcache("SimplePageCachingFilter")); 26 27// 添加数据到缓存中 28 29Element element = new Element("key", "val"); 30 31sample.put(element); 32 33// 获取缓存中的对象,注意添加到cache中对象要序列化 实现Serializable接口 34 35Element result = sample.get("key"); 36 37// 删除缓存 38 39sample.remove("key"); 40 41sample.removeAll(); 42 43// 获取缓存管理器中的缓存配置名称 44 45for (String cacheName : cacheManager.getCacheNames()) { 46 47System.out.println(cacheName); 48 49} 50 51// 获取所有的缓存对象 52 53for (Object key : cache.getKeys()) { 54 55System.out.println(key); 56 57} 58 59// 得到缓存中的对象数 60 61cache.getSize(); 62 63// 得到缓存对象占用内存的大小 64 65cache.getMemoryStoreSize(); 66 67// 得到缓存读取的命中次数 68 69cache.getStatistics().getCacheHits(); 70 71// 得到缓存读取的错失次数 72 73cache.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。

具体实现参考:

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;

}

在ehcache.xml中加入如下配置

1<?xml version="1.0" encoding="gbk"?> 2 3<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"> 4 5<diskStore path="java.io.tmpdir"/> 6 7<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="30" timeToLiveSeconds="30" overflowToDisk="false"/> 8 9<!-- 10 11 配置自定义缓存 12 13 maxElementsInMemory:缓存中允许创建的最大对象数 14 15 eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。 16 17 timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前, 18 19 两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效, 20 21 如果该值是 0 就意味着元素可以停顿无穷长的时间。 22 23 timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值, 24 25 这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。 26 27 overflowToDisk:内存不足时,是否启用磁盘缓存。 28 29 memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。 30 31 --> 32 33<cache name="SimplePageCachingFilter" 34 35maxElementsInMemory="10000" 36 37eternal="false" 38 39overflowToDisk="false" 40 41timeToIdleSeconds="900" 42 43timeToLiveSeconds="1800" 44 45memoryStoreEvictionPolicy="LFU" /> 46 47</ehcache>

具体代码:

1package com.hoo.ehcache.filter; 2 3import java.util.Enumeration; 4 5import javax.servlet.FilterChain; 6 7import javax.servlet.http.HttpServletRequest; 8 9import javax.servlet.http.HttpServletResponse; 10 11import net.sf.ehcache.CacheException; 12 13import net.sf.ehcache.constructs.blocking.LockTimeoutException; 14 15import net.sf.ehcache.constructs.web.AlreadyCommittedException; 16 17import net.sf.ehcache.constructs.web.AlreadyGzippedException; 18 19import net.sf.ehcache.constructs.web.filter.FilterNonReentrantException; 20 21import net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter; 22 23import org.apache.commons.lang.StringUtils; 24 25import org.apache.log4j.Logger; 26 27/** 28 29 * <b>function:</b> mobile 页面缓存过滤器 30 31 * @author hoojo 32 33 * @createDate 2012-7-4 上午09:34:30 34 35 * @file PageEhCacheFilter.java 36 37 * @package com.hoo.ehcache.filter 38 39 * @project Ehcache 40 41 * @blog http://blog.csdn.net/IBM_hoojo 42 43 * @email hoojo_@126.com 44 45 * @version 1.0 46 47 */ 48 49public class PageEhCacheFilter extends SimplePageCachingFilter { 50 51private final static Logger log = Logger.getLogger(PageEhCacheFilter.class); 52 53private final static String FILTER_URL_PATTERNS = "patterns"; 54 55private static String[] cacheURLs; 56 57private void init() throws CacheException { 58 59String patterns = filterConfig.getInitParameter(FILTER_URL_PATTERNS); 60 61cacheURLs = StringUtils.split(patterns, ","); 62 63} 64 65@Override 66 67protected void doFilter(final HttpServletRequest request, 68 69final HttpServletResponse response, final FilterChain chain) 70 71throws AlreadyGzippedException, AlreadyCommittedException, 72 73FilterNonReentrantException, LockTimeoutException, Exception { 74 75if (cacheURLs == null) { 76 77init(); 78 79} 80 81String url = request.getRequestURI(); 82 83boolean flag = false; 84 85if (cacheURLs != null && cacheURLs.length > 0) { 86 87for (String cacheURL : cacheURLs) { 88 89if (url.contains(cacheURL.trim())) { 90 91flag = true; 92 93break; 94 95} 96 97} 98 99} 100 101// 如果包含我们要缓存的url 就缓存该页面,否则执行正常的页面转向 102 103if (flag) { 104 105String query = request.getQueryString(); 106 107if (query != null) { 108 109query = "?" + query; 110 111} 112 113log.info("当前请求被缓存:" + url + query); 114 115super.doFilter(request, response, chain); 116 117} else { 118 119chain.doFilter(request, response); 120 121} 122 123} 124 125@SuppressWarnings("unchecked") 126 127private boolean headerContains(final HttpServletRequest request, final String header, final String value) { 128 129logRequestHeaders(request); 130 131final Enumeration accepted = request.getHeaders(header); 132 133while (accepted.hasMoreElements()) { 134 135final String headerValue = (String) accepted.nextElement(); 136 137if (headerValue.indexOf(value) != -1) { 138 139return true; 140 141} 142 143} 144 145return false; 146 147} 148 149/** 150 151 * @see net.sf.ehcache.constructs.web.filter.Filter#acceptsGzipEncoding(javax.servlet.http.HttpServletRequest) 152 153 * <b>function:</b> 兼容ie6/7 gzip压缩 154 155 * @author hoojo 156 157 * @createDate 2012-7-4 上午11:07:11 158 159 */ 160 161@Override 162 163protected boolean acceptsGzipEncoding(HttpServletRequest request) { 164 165boolean ie6 = headerContains(request, "User-Agent", "MSIE 6.0"); 166 167boolean ie7 = headerContains(request, "User-Agent", "MSIE 7.0"); 168 169return acceptsEncoding(request, "gzip") || ie6 || ie7; 170 171} 172 173}

这里的PageEhCacheFilter继承了SimplePageCachingFilter,一般情况下SimplePageCachingFilter就够用了,这里是为了满足当前系统需求才做了覆盖操作。使用SimplePageCachingFilter需要在web.xml中配置cacheName,cacheName默认是SimplePageCachingFilter,对应ehcache.xml中的cache配置。

在web.xml中加入如下配置

1<!-- 缓存、gzip压缩核心过滤器 --> 2 3<filter> 4 5<filter-name>PageEhCacheFilter</filter-name> 6 7<filter-class>com.hoo.ehcache.filter.PageEhCacheFilter</filter-class> 8 9<init-param> 10 11<param-name>patterns</param-name> 12 13<!-- 配置你需要缓存的url --> 14 15<param-value>/cache.jsp, product.action, market.action </param-value> 16 17</init-param> 18 19</filter> 20 21<filter-mapping> 22 23<filter-name>PageEhCacheFilter</filter-name> 24 25<url-pattern>*.action</url-pattern> 26 27</filter-mapping> 28 29<filter-mapping> 30 31<filter-name>PageEhCacheFilter</filter-name> 32 33<url-pattern>*.jsp</url-pattern> 34 35</filter-mapping>

当第一次请求这些页面后,这些页面就会被添加到缓存中,以后请求这些页面将会从缓存中获取。你可以在cache.jsp页面中用小脚本来测试该页面是否被缓存。<%=new Date()%>如果时间是变动的,则表示该页面没有被缓存或是缓存已经过期,否则则是在缓存状态了。

四、对象缓存

对象缓存就是将查询的数据,添加到缓存中,下次再次查询的时候直接从缓存中获取,而不去数据库中查询。

对象缓存一般是针对方法、类而来的,结合Spring的Aop对象、方法缓存就很简单。这里需要用到切面编程,用到了Spring的MethodInterceptor或是用@Aspect。

代码如下:

1package com.hoo.common.ehcache; 2 3import java.io.Serializable; 4 5import net.sf.ehcache.Cache; 6 7import net.sf.ehcache.Element; 8 9import org.aopalliance.intercept.MethodInterceptor; 10 11import org.aopalliance.intercept.MethodInvocation; 12 13import org.apache.log4j.Logger; 14 15import org.springframework.beans.factory.InitializingBean; 16 17/** 18 19 * <b>function:</b> 缓存方法拦截器核心代码 20 21 * @author hoojo 22 23 * @createDate 2012-7-2 下午06:05:34 24 25 * @file MethodCacheInterceptor.java 26 27 * @package com.hoo.common.ehcache 28 29 * @project Ehcache 30 31 * @blog http://blog.csdn.net/IBM_hoojo 32 33 * @email hoojo_@126.com 34 35 * @version 1.0 36 37 */ 38 39public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean { 40 41private static final Logger log = Logger.getLogger(MethodCacheInterceptor.class); 42 43private Cache cache; 44 45public void setCache(Cache cache) { 46 47this.cache = cache; 48 49} 50 51public void afterPropertiesSet() throws Exception { 52 53log.info(cache + " A cache is required. Use setCache(Cache) to provide one."); 54 55} 56 57public Object invoke(MethodInvocation invocation) throws Throwable { 58 59String targetName = invocation.getThis().getClass().getName(); 60 61String methodName = invocation.getMethod().getName(); 62 63Object[] arguments = invocation.getArguments(); 64 65Object result; 66 67String cacheKey = getCacheKey(targetName, methodName, arguments); 68 69Element element = null; 70 71synchronized (this) { 72 73element = cache.get(cacheKey); 74 75if (element == null) { 76 77log.info(cacheKey + "加入到缓存: " + cache.getName()); 78 79// 调用实际的方法 80 81result = invocation.proceed(); 82 83element = new Element(cacheKey, (Serializable) result); 84 85cache.put(element); 86 87} else { 88 89log.info(cacheKey + "使用缓存: " + cache.getName()); 90 91} 92 93} 94 95return element.getValue(); 96 97} 98 99/** 100 101 * <b>function:</b> 返回具体的方法全路径名称 参数 102 103 * @author hoojo 104 105 * @createDate 2012-7-2 下午06:12:39 106 107 * @param targetName 全路径 108 109 * @param methodName 方法名称 110 111 * @param arguments 参数 112 113 * @return 完整方法名称 114 115 */ 116 117private String getCacheKey(String targetName, String methodName, Object[] arguments) { 118 119StringBuffer sb = new StringBuffer(); 120 121sb.append(targetName).append(".").append(methodName); 122 123if ((arguments != null) && (arguments.length != 0)) { 124 125for (int i = 0; i < arguments.length; i++) { 126 127sb.append(".").append(arguments[i]); 128 129} 130 131} 132 133return sb.toString(); 134 135} 136 137}

这里的方法拦截器主要是对你要拦截的类的方法进行拦截,然后判断该方法的类路径+方法名称+参数值组合的cache key在缓存cache中是否存在。如果存在就从缓存中取出该对象,转换成我们要的返回类型。没有的话就把该方法返回的对象添加到缓存中即可。值得主意的是当前方法的参数和返回值的对象类型需要序列化。

我们需要在src目录下添加applicationContext.xml完成对MethodCacheInterceptor拦截器的配置,该配置主意是注入我们的cache对象,哪个cache来管理对象缓存,然后哪些类、方法参与该拦截器的扫描。

添加配置如下:

1<context:component-scan base-package="com.hoo.common.interceptor"/> 2 3<!-- 配置eh缓存管理器 --> 4 5<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/> 6 7<!-- 配置一个简单的缓存工厂bean对象 --> 8 9<bean id="simpleCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> 10 11<property name="cacheManager" ref="cacheManager" /> 12 13<!-- 使用缓存 关联ehcache.xml中的缓存配置 --> 14 15<property name="cacheName" value="mobileCache" /> 16 17</bean> 18 19<!-- 配置一个缓存拦截器对象,处理具体的缓存业务 --> 20 21<bean id="methodCacheInterceptor" class="com. hoo.common.interceptor.MethodCacheInterceptor"> 22 23<property name="cache" ref="simpleCache"/> 24 25</bean> 26 27<!-- 参与缓存的切入点对象 (切入点对象,确定何时何地调用拦截器) --> 28 29<bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> 30 31<!-- 配置缓存aop切面 --> 32 33<property name="advice" ref="methodCacheInterceptor" /> 34 35<!-- 配置哪些方法参与缓存策略 --> 36 37<!-- 38 39 .表示符合任何单一字元 40 41 ### +表示符合前一个字元一次或多次 42 43 ### *表示符合前一个字元零次或多次 44 45 ### \Escape任何Regular expression使用到的符号 46 47 --> 48 49<!-- .*表示前面的前缀(包括包名) 表示print方法--> 50 51<property name="patterns"> 52 53<list> 54 55<value>com.hoo.rest.*RestService*\.*get.*</value> 56 57<value>com.hoo.rest.*RestService*\.*search.*</value> 58 59</list> 60 61</property> 62 63</bean>

在ehcache.xml中添加如下cache配置

1<cache name="mobileCache" 2 3maxElementsInMemory="10000" 4 5eternal="false" 6 7overflowToDisk="true" 8 9timeToIdleSeconds="1800" 10 11timeToLiveSeconds="3600" 12 13memoryStoreEvictionPolicy="LFU" />

作者:hoojo
出处: http://www.blogjava.net/hoojo/archive/2012/07/12/382852.html
blog:http://blog.csdn.net/IBM_hoojo
         http://hoojo.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )