一、準(zhǔn)備工作如果你的系統(tǒng)中已經(jīng)成功加入Spring、Hibernate;那么你就可以進(jìn)入下面Ehcache的準(zhǔn)備工作。 1、 下載jar包
2、 需要添加如下jar包到lib目錄下
3、 當(dāng)前工程的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配置文件中的一個(gè)cache Cache sample = cacheManager.getCache("sample"); // 獲取頁面緩存 BlockingCache cache = new BlockingCache(cacheManager.getEhcache("SimplePageCachingFilter")); // 添加數(shù)據(jù)到緩存中 Element element = new Element("key", "val"); sample.put(element); // 獲取緩存中的對象,注意添加到cache中對象要序列化 實(shí)現(xiàn)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); } // 得到緩存中的對象數(shù) cache.getSize(); // 得到緩存對象占用內(nèi)存的大小 cache.getMemoryStoreSize(); // 得到緩存讀取的命中次數(shù) cache.getStatistics().getCacheHits(); // 得到緩存讀取的錯(cuò)失次數(shù) cache.getStatistics().getCacheMisses(); 三、頁面緩存
在使用Gzip壓縮時(shí),需注意兩個(gè)問題:
在ehcache.xml中加入如下配置 <?xml version="1.0" encoding="gbk"?> <ehcache xmlns:xsi="http://www./2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="30" timeToLiveSeconds="30" overflowToDisk="false"/> <!-- 配置自定義緩存 maxElementsInMemory:緩存中允許創(chuàng)建的最大對象數(shù) eternal:緩存中對象是否為永久的,如果是,超時(shí)設(shè)置將被忽略,對象從不過期。 timeToIdleSeconds:緩存數(shù)據(jù)的鈍化時(shí)間,也就是在一個(gè)元素消亡之前, 兩次訪問時(shí)間的最大時(shí)間間隔值,這只能在元素不是永久駐留時(shí)有效, 如果該值是 0 就意味著元素可以停頓無窮長的時(shí)間。 timeToLiveSeconds:緩存數(shù)據(jù)的生存時(shí)間,也就是一個(gè)元素從構(gòu)建到消亡的最大時(shí)間間隔值, 這只能在元素不是永久駐留時(shí)有效,如果該值是0就意味著元素可以停頓無窮長的時(shí)間。 overflowToDisk:內(nèi)存不足時(shí),是否啟用磁盤緩存。 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 就緩存該頁面,否則執(zhí)行正常的頁面轉(zhuǎn)向 if (flag) { String query = request.getQueryString(); if (query != null) { query = "?" query; } log.info("當(dāng)前請求被緩存:" 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; } }
在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>
四、對象緩存
代碼如下: 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()); // 調(diào)用實(shí)際的方法 result = invocation.proceed(); element = new Element(cacheKey, (Serializable) result); cache.put(element); } else { log.info(cacheKey "使用緩存: " cache.getName()); } } return element.getValue(); } /** * <b>function:</b> 返回具體的方法全路徑名稱 參數(shù) * @author hoojo * @createDate 2012-7-2 下午06:12:39 * @param targetName 全路徑 * @param methodName 方法名稱 * @param arguments 參數(shù) * @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(); } }
添加配置如下: <context:component-scan base-package="com.hoo.common.interceptor"/> <!-- 配置eh緩存管理器 --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"/> <!-- 配置一個(gè)簡單的緩存工廠bean對象 --> <bean id="simpleCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"> <property name="cacheManager" ref="cacheManager" /> <!-- 使用緩存 關(guān)聯(lián)ehcache.xml中的緩存配置 --> <property name="cacheName" value="mobileCache" /> </bean> <!-- 配置一個(gè)緩存攔截器對象,處理具體的緩存業(yè)務(wù) --> <bean id="methodCacheInterceptor" class="com. hoo.common.interceptor.MethodCacheInterceptor"> <property name="cache" ref="simpleCache"/> </bean> <!-- 參與緩存的切入點(diǎn)對象 (切入點(diǎn)對象,確定何時(shí)何地調(diào)用攔截器) --> <bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"> <!-- 配置緩存aop切面 --> <property name="advice" ref="methodCacheInterceptor" /> <!-- 配置哪些方法參與緩存策略 --> <!-- .表示符合任何單一字元 ### 表示符合前一個(gè)字元一次或多次 ### *表示符合前一個(gè)字元零次或多次 ### \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" /> |
|