Ehcache 整合Spring 使用頁面、對象緩存java
Ehcache在不少項目中都出現過,用法也比較簡單。通常的加些配置就能夠了,並且Ehcache能夠對頁面、對象、數據進行緩存,同時支持集羣/分佈式緩存。若是整合Spring、Hibernate也很是的簡單,Spring對Ehcache的支持也很是好。EHCache支持內存和磁盤的緩存,支持LRU、LFU和FIFO多種淘汰算法,支持分佈式的Cache,能夠做爲Hibernate的緩存插件。同時它也能提供基於Filter的Cache,該Filter能夠緩存響應的內容並採用Gzip壓縮提升響應速度。web
Email:hoojo_@126.com算法
Blog:http://blog.csdn.net/IBM_hoojospring
http://hoojo.cnblogs.com/數據庫
1、準備工做express
若是你的系統中已經成功加入Spring、Hibernate;那麼你就能夠進入下面Ehcache的準備工做。apache
一、 下載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緩存
二、 須要添加以下jar包到lib目錄下
ehcache-core-2.5.2.jar
ehcache-web-2.0.4.jar 主要針對頁面緩存
三、 當前工程的src目錄中加入配置文件
ehcache.xml
ehcache.xsd
這些配置文件在ehcache-core這個jar包中能夠找到
2、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();
3、頁面緩存
頁面緩存主要用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中加入以下配置 <?xml version="1.0" encoding="gbk"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="30" timeToLiveSeconds="30" overflowToDisk="false"/> <!-- 配置自定義緩存 maxElementsInMemory:緩存中容許建立的最大對象數 eternal:緩存中對象是否爲永久的,若是是,超時設置將被忽略,對象從不過時。 timeToIdleSeconds:緩存數據的鈍化時間,也就是在一個元素消亡以前, 兩次訪問時間的最大時間間隔值,這隻能在元素不是永久駐留時有效, 若是該值是 0 就意味着元素能夠停頓無窮長的時間。 timeToLiveSeconds:緩存數據的生存時間,也就是一個元素從構建到消亡的最大時間間隔值, 這隻能在元素不是永久駐留時有效,若是該值是0就意味着元素能夠停頓無窮長的時間。 overflowToDisk:內存不足時,是否啓用磁盤緩存。 memoryStoreEvictionPolicy:緩存滿了以後的淘汰算法。 --> <cache name="SimplePageCachingFilter" maxElementsInMemory="10000" eternal="false" overflowToDisk="false" timeToIdleSeconds="900" timeToLiveSeconds="1800" memoryStoreEvictionPolicy="LFU" /> </ehcache>
具體代碼: package com.hoo.ehcache.filter; 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; /** * <b>function:</b> mobile 頁面緩存過濾器 * @author hoojo * @createDate 2012-7-4 上午09:34:30 * @file PageEhCacheFilter.java * @package com.hoo.ehcache.filter * @project Ehcache * @blog http://blog.csdn.net/IBM_hoojo * @email hoojo_@126.com * @version 1.0 */ 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; } /** * @see net.sf.ehcache.constructs.web.filter.Filter#acceptsGzipEncoding(javax.servlet.http.HttpServletRequest) * <b>function:</b> 兼容ie6/7 gzip壓縮 * @author hoojo * @createDate 2012-7-4 上午11:07:11 */ @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; } }
這裏的PageEhCacheFilter繼承了SimplePageCachingFilter,通常狀況下SimplePageCachingFilter就夠用了,這裏是爲了知足當前系統需求才作了覆蓋操做。使用SimplePageCachingFilter須要在web.xml中配置cacheName,cacheName默認是SimplePageCachingFilter,對應ehcache.xml中的cache配置。
在web.xml中加入以下配置
<!-- 緩存、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>
當第一次請求這些頁面後,這些頁面就會被添加到緩存中,之後請求這些頁面將會從緩存中獲取。你能夠在cache.jsp頁面中用小腳原本測試該頁面是否被緩存。<%=new Date()%>若是時間是變更的,則表示該頁面沒有被緩存或是緩存已通過期,不然則是在緩存狀態了。
4、對象緩存
對象緩存就是將查詢的數據,添加到緩存中,下次再次查詢的時候直接從緩存中獲取,而不去數據庫中查詢。
對象緩存通常是針對方法、類而來的,結合Spring的Aop對象、方法緩存就很簡單。這裏須要用到切面編程,用到了Spring的MethodInterceptor或是用@Aspect。
代碼以下:
package com.hoo.common.ehcache; 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; /** * <b>function:</b> 緩存方法攔截器核心代碼 * @author hoojo * @createDate 2012-7-2 下午06:05:34 * @file MethodCacheInterceptor.java * @package com.hoo.common.ehcache * @project Ehcache * @blog http://blog.csdn.net/IBM_hoojo * @email hoojo_@126.com * @version 1.0 */ 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."); } 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> 返回具體的方法全路徑名稱 參數 * @author hoojo * @createDate 2012-7-2 下午06:12:39 * @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中是否存在。若是存在就從緩存中取出該對象,轉換成咱們要的返回類型。沒有的話就把該方法返回的對象添加到緩存中便可。值得主意的是當前方法的參數和返回值的對象類型須要序列化。
咱們須要在src目錄下添加applicationContext.xml完成對MethodCacheInterceptor攔截器的配置,該配置主意是注入咱們的cache對象,哪一個cache來管理對象緩存,而後哪些類、方法參與該攔截器的掃描。
添加配置以下:
<context:component-scan base-package="com.hoo.common.interceptor"/> <!-- 配置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="mobileCache" /> </bean> <!-- 配置一個緩存攔截器對象,處理具體的緩存業務 --> <bean id="methodCacheInterceptor" class="com. hoo.common.interceptor.MethodCacheInterceptor"> <property name="cache" ref="simpleCache"/> </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.hoo.rest.*RestService*\.*get.*</value> <value>com.hoo.rest.*RestService*\.*search.*</value> </list> </property> </bean> 在ehcache.xml中添加以下cache配置 <cache name="mobileCache" maxElementsInMemory="10000" eternal="false" overflowToDisk="true" timeToIdleSeconds="1800" timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LFU" />