日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Spring中集成Ehcache使用頁面、對(duì)象緩存

Ehcache在很多項(xiàng)目中都出現(xiàn)過,用法也比較簡單。一般的加些配置就可以了,而且Ehcache可以對(duì)頁面、對(duì)象、數(shù)據(jù)進(jìn)行緩存,同時(shí)支持集群/分布式緩存。如果整合Spring、Hibernate也非常的簡單,Spring對(duì)Ehcache的支持也非常好。EHCache支持內(nèi)存和磁盤的緩存,支持LRU、LFU和FIFO多種淘汰算法,支持分布式的Cache,可以作為Hibernate的緩存插件。同時(shí)它也能提供基于Filter的Cache,該Filter可以緩存響應(yīng)的內(nèi)容并采用Gzip壓縮提高響應(yīng)速度。

成都創(chuàng)新互聯(lián)公司是一家專注于做網(wǎng)站、成都網(wǎng)站建設(shè)與策劃設(shè)計(jì),宿城網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)十載,網(wǎng)設(shè)計(jì)領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:宿城等地區(qū)。宿城做網(wǎng)站價(jià)格咨詢:18980820575

Email:hoojo_@126.com

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

http://hoojo.cnblogs.com/

一、準(zhǔn)備工作

如果你的系統(tǒng)中已經(jīng)成功加入Spring、Hibernate;那么你就可以進(jìn)入下面Ehcache的準(zhǔn)備工作。

1、 下載jar包

Ehcache 對(duì)象、數(shù)據(jù)緩存: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 主要針對(duì)頁面緩存

3、 當(dāng)前工程的src目錄中加入配置文件

 ehcache.xml

ehcache.xsd

這些配置文件在ehcache-core這個(gè)jar包中可以找到

二、Ehcache基本用法

 
 
  1. CacheManager cacheManager = CacheManager.create(); 
  2. // 或者 
  3. cacheManager = CacheManager.getInstance(); 
  4. // 或者 
  5. cacheManager = CacheManager.create("/config/ehcache.xml"); 
  6. // 或者 
  7. cacheManager = CacheManager.create("http://localhost:8080/test/ehcache.xml"); 
  8. cacheManager = CacheManager.newInstance("/config/ehcache.xml"); 
  9. // ....... 
  10.   
  11. // 獲取ehcache配置文件中的一個(gè)cache 
  12. Cache sample = cacheManager.getCache("sample"); 
  13. // 獲取頁面緩存 
  14. BlockingCache cache = new BlockingCache(cacheManager.getEhcache("SimplePageCachingFilter")); 
  15. // 添加數(shù)據(jù)到緩存中 
  16. Element element = new Element("key", "val"); 
  17. sample.put(element); 
  18. // 獲取緩存中的對(duì)象,注意添加到cache中對(duì)象要序列化 實(shí)現(xiàn)Serializable接口 
  19. Element result = sample.get("key"); 
  20. // 刪除緩存 
  21. sample.remove("key"); 
  22. sample.removeAll(); 
  23.   
  24. // 獲取緩存管理器中的緩存配置名稱 
  25. for (String cacheName : cacheManager.getCacheNames()) { 
  26.     System.out.println(cacheName); 
  27. // 獲取所有的緩存對(duì)象 
  28. for (Object key : cache.getKeys()) { 
  29.     System.out.println(key); 
  30.   
  31. // 得到緩存中的對(duì)象數(shù) 
  32. cache.getSize(); 
  33. // 得到緩存對(duì)象占用內(nèi)存的大小 
  34. cache.getMemoryStoreSize(); 
  35. // 得到緩存讀取的命中次數(shù) 
  36. cache.getStatistics().getCacheHits(); 
  37. // 得到緩存讀取的錯(cuò)失次數(shù) 
  38. cache.getStatistics().getCacheMisses(); 

三、頁面緩存

頁面緩存主要用Filter過濾器對(duì)請(qǐng)求的url進(jìn)行過濾,如果該url在緩存中出現(xiàn)。那么頁面數(shù)據(jù)就從緩存對(duì)象中獲取,并以gzip壓縮后返回。其速度是沒有壓縮緩存時(shí)速度的3-5倍,效率相當(dāng)之高!其中頁面緩存的過濾器有CachingFilter,一般要擴(kuò)展filter或是自定義Filter都繼承該CachingFilter。

CachingFilter功能可以對(duì)HTTP響應(yīng)的內(nèi)容進(jìn)行緩存。這種方式緩存數(shù)據(jù)的粒度比較粗,例如緩存整張頁面。它的優(yōu)點(diǎn)是使用簡單、效率高,缺點(diǎn)是不夠靈活,可重用程度不高。

EHCache使用SimplePageCachingFilter類實(shí)現(xiàn)Filter緩存。該類繼承自CachingFilter,有默認(rèn)產(chǎn)生cache key的calculateKey()方法,該方法使用HTTP請(qǐng)求的URI和查詢條件來組成key。也可以自己實(shí)現(xiàn)一個(gè)Filter,同樣繼承CachingFilter類,然后覆寫calculateKey()方法,生成自定義的key。

CachingFilter輸出的數(shù)據(jù)會(huì)根據(jù)瀏覽器發(fā)送的Accept-Encoding頭信息進(jìn)行Gzip壓縮。

在使用Gzip壓縮時(shí),需注意兩個(gè)問題:

1. Filter在進(jìn)行Gzip壓縮時(shí),采用系統(tǒng)默認(rèn)編碼,對(duì)于使用GBK編碼的中文網(wǎng)頁來說,需要將操作系統(tǒng)的語言設(shè)置為:zh_CN.GBK,否則會(huì)出現(xiàn)亂碼的問題。

2. 默認(rèn)情況下CachingFilter會(huì)根據(jù)瀏覽器發(fā)送的請(qǐng)求頭部所包含的Accept-Encoding參數(shù)值來判斷是否進(jìn)行Gzip壓縮。雖然IE6/7瀏覽器是支持Gzip壓縮的,但是在發(fā)送請(qǐng)求的時(shí)候卻不帶該參數(shù)。為了對(duì)IE6/7也能進(jìn)行Gzip壓縮,可以通過繼承CachingFilter,實(shí)現(xiàn)自己的Filter,然后在具體的實(shí)現(xiàn)中覆寫方法acceptsGzipEncoding。

具體實(shí)現(xiàn)參考:

 
 
  1. protected boolean acceptsGzipEncoding(HttpServletRequest request) { 
  2.  
  3. boolean ie6 = headerContains(request, "User-Agent", "MSIE 6.0"); 
  4.  
  5. boolean ie7 = headerContains(request, "User-Agent", "MSIE 7.0"); 
  6.  
  7. return acceptsEncoding(request, "gzip") || ie6 || ie7; 
  8.  

在ehcache.xml中加入如下配置

 
 
  1.  
  2.  
  3.      
  4.  
  5.      
  6.      
  7.     
  8.         maxElementsInMemory="10000"  
  9.         eternal="false" 
  10.         overflowToDisk="false"  
  11.         timeToIdleSeconds="900"  
  12.         timeToLiveSeconds="1800" 
  13.         memoryStoreEvictionPolicy="LFU" /> 
  14.  
  15.  

具體代碼:

 
 
  1. package com.hoo.ehcache.filter; 
  2.  
  3. import java.util.Enumeration; 
  4. import javax.servlet.FilterChain; 
  5. import javax.servlet.http.HttpServletRequest; 
  6. import javax.servlet.http.HttpServletResponse; 
  7. import net.sf.ehcache.CacheException; 
  8. import net.sf.ehcache.constructs.blocking.LockTimeoutException; 
  9. import net.sf.ehcache.constructs.web.AlreadyCommittedException; 
  10. import net.sf.ehcache.constructs.web.AlreadyGzippedException; 
  11. import net.sf.ehcache.constructs.web.filter.FilterNonReentrantException; 
  12. import net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter; 
  13. import org.apache.commons.lang.StringUtils; 
  14. import org.apache.log4j.Logger; 
  15.  
  16. /** 
  17.  * function: mobile 頁面緩存過濾器 
  18.  * @author hoojo 
  19.  * @createDate 2012-7-4 上午09:34:30 
  20.  * @file PageEhCacheFilter.java 
  21.  * @package com.hoo.ehcache.filter 
  22.  * @project Ehcache 
  23.  * @blog http://blog.csdn.net/IBM_hoojo 
  24.  * @email hoojo_@126.com 
  25.  * @version 1.0 
  26.  */ 
  27. public class PageEhCacheFilter extends SimplePageCachingFilter { 
  28.  
  29.     private final static Logger log = Logger.getLogger(PageEhCacheFilter.class); 
  30.  
  31.     private final static String FILTER_URL_PATTERNS = "patterns"; 
  32.     private static String[] cacheURLs; 
  33.  
  34.     private void init() throws CacheException { 
  35.         String patterns = filterConfig.getInitParameter(FILTER_URL_PATTERNS); 
  36.         cacheURLs = StringUtils.split(patterns, ","); 
  37.     } 
  38.  
  39.     @Override 
  40.     protected void doFilter(final HttpServletRequest request, 
  41.             final HttpServletResponse response, final FilterChain chain) 
  42.             throws AlreadyGzippedException, AlreadyCommittedException, 
  43.             FilterNonReentrantException, LockTimeoutException, Exception { 
  44.         if (cacheURLs == null) { 
  45.             init(); 
  46.         } 
  47.  
  48.         String url = request.getRequestURI(); 
  49.         boolean flag = false; 
  50.         if (cacheURLs != null && cacheURLs.length > 0) { 
  51.             for (String cacheURL : cacheURLs) { 
  52.                 if (url.contains(cacheURL.trim())) { 
  53.                     flag = true; 
  54.                     break; 
  55.                 } 
  56.             } 
  57.         } 
  58.         // 如果包含我們要緩存的url 就緩存該頁面,否則執(zhí)行正常的頁面轉(zhuǎn)向 
  59.         if (flag) { 
  60.             String query = request.getQueryString(); 
  61.             if (query != null) { 
  62.                 query = "?" + query; 
  63.             } 
  64.             log.info("當(dāng)前請(qǐng)求被緩存:" + url + query); 
  65.             super.doFilter(request, response, chain); 
  66.         } else { 
  67.             chain.doFilter(request, response); 
  68.         } 
  69.     } 
  70.  
  71.     @SuppressWarnings("unchecked") 
  72.     private boolean headerContains(final HttpServletRequest request, final String header, final String value) { 
  73.         logRequestHeaders(request); 
  74.         final Enumeration accepted = request.getHeaders(header); 
  75.         while (accepted.hasMoreElements()) { 
  76.             final String headerValue = (String) accepted.nextElement(); 
  77.             if (headerValue.indexOf(value) != -1) { 
  78.                 return true; 
  79.             } 
  80.         } 
  81.         return false; 
  82.     } 
  83.  
  84.     /** 
  85.      * @see net.sf.ehcache.constructs.web.filter.Filter#acceptsGzipEncoding(javax.servlet.http.HttpServletRequest) 
  86.      * function: 兼容ie6/7 gzip壓縮 
  87.      * @author hoojo 
  88.      * @createDate 2012-7-4 上午11:07:11 
  89.      */ 
  90.     @Override 
  91.     protected boolean acceptsGzipEncoding(HttpServletRequest request) { 
  92.         boolean ie6 = headerContains(request, "User-Agent", "MSIE 6.0"); 
  93.         boolean ie7 = headerContains(request, "User-Agent", "MSIE 7.0"); 
  94.         return acceptsEncoding(request, "gzip") || ie6 || ie7; 
  95.     } 
  96. 這里的PageEhCacheFilter繼承了SimplePageCachingFilter,一般情況下SimplePageCachingFilter就夠用了,這里是為了滿足當(dāng)前系統(tǒng)需求才做了覆蓋操作。使用SimplePageCachingFilter需要在web.xml中配置cacheName,cacheName默認(rèn)是SimplePageCachingFilter,對(duì)應(yīng)ehcache.xml中的cache配置。 
  97.  
  98. 在web.xml中加入如下配置 
  99.  
  100.  
  101.  
  102.     PageEhCacheFilter 
  103.     com.hoo.ehcache.filter.PageEhCacheFilter 
  104.      
  105.         patterns 
  106.          
  107.         /cache.jsp, product.action, market.action  
  108.      
  109.  
  110.  
  111.     PageEhCacheFilter 
  112.     *.action 
  113.  
  114.  
  115.     PageEhCacheFilter 
  116.     *.jsp 
  117.  
  118. 當(dāng)***次請(qǐng)求這些頁面后,這些頁面就會(huì)被添加到緩存中,以后請(qǐng)求這些頁面將會(huì)從緩存中獲取。你可以在cache.jsp頁面中用小腳本來測試該頁面是否被緩存。<%=new Date()%>如果時(shí)間是變動(dòng)的,則表示該頁面沒有被緩存或是緩存已經(jīng)過期,否則則是在緩存狀態(tài)了。 
  119.  
  120. 四、對(duì)象緩存 
  121.  
  122. 對(duì)象緩存就是將查詢的數(shù)據(jù),添加到緩存中,下次再次查詢的時(shí)候直接從緩存中獲取,而不去數(shù)據(jù)庫中查詢。 
  123.  
  124. 對(duì)象緩存一般是針對(duì)方法、類而來的,結(jié)合Spring的Aop對(duì)象、方法緩存就很簡單。這里需要用到切面編程,用到了Spring的MethodInterceptor或是用@Aspect。 
  125.  
  126. 代碼如下: 
  127.  
  128. package com.hoo.common.ehcache; 
  129.  
  130. import java.io.Serializable; 
  131. import net.sf.ehcache.Cache; 
  132. import net.sf.ehcache.Element; 
  133. import org.aopalliance.intercept.MethodInterceptor; 
  134. import org.aopalliance.intercept.MethodInvocation; 
  135. import org.apache.log4j.Logger; 
  136. import org.springframework.beans.factory.InitializingBean; 
  137.  
  138. /** 
  139.  * function: 緩存方法攔截器核心代碼  
  140.  * @author hoojo 
  141.  * @createDate 2012-7-2 下午06:05:34 
  142.  * @file MethodCacheInterceptor.java 
  143.  * @package com.hoo.common.ehcache 
  144.  * @project Ehcache 
  145.  * @blog http://blog.csdn.net/IBM_hoojo 
  146.  * @email hoojo_@126.com 
  147.  * @version 1.0 
  148.  */ 
  149. public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean { 
  150.  
  151.     private static final Logger log = Logger.getLogger(MethodCacheInterceptor.class); 
  152.  
  153.     private Cache cache; 
  154.  
  155.     public void setCache(Cache cache) { 
  156.         this.cache = cache; 
  157.     } 
  158.  
  159.     public void afterPropertiesSet() throws Exception { 
  160.         log.info(cache + " A cache is required. Use setCache(Cache) to provide one."); 
  161.     } 
  162.  
  163.     public Object invoke(MethodInvocation invocation) throws Throwable { 
  164.         String targetName = invocation.getThis().getClass().getName(); 
  165.         String methodName = invocation.getMethod().getName(); 
  166.         Object[] arguments = invocation.getArguments(); 
  167.         Object result; 
  168.  
  169.         String cacheKey = getCacheKey(targetName, methodName, arguments); 
  170.         Element element = null; 
  171.         synchronized (this) { 
  172.             element = cache.get(cacheKey); 
  173.             if (element == null) { 
  174.                 log.info(cacheKey + "加入到緩存: " + cache.getName()); 
  175.                 // 調(diào)用實(shí)際的方法 
  176.                 result = invocation.proceed(); 
  177.                 element = new Element(cacheKey, (Serializable) result); 
  178.                 cache.put(element); 
  179.             } else { 
  180.                 log.info(cacheKey + "使用緩存: " + cache.getName()); 
  181.             } 
  182.         } 
  183.         return element.getValue(); 
  184.     } 
  185.  
  186.     /** 
  187.      * function: 返回具體的方法全路徑名稱 參數(shù) 
  188.      * @author hoojo 
  189.      * @createDate 2012-7-2 下午06:12:39 
  190.      * @param targetName 全路徑 
  191.      * @param methodName 方法名稱 
  192.      * @param arguments 參數(shù) 
  193.      * @return 完整方法名稱 
  194.      */ 
  195.     private String getCacheKey(String targetName, String methodName, Object[] arguments) { 
  196.         StringBuffer sb = new StringBuffer(); 
  197.         sb.append(targetName).append(".").append(methodName); 
  198.         if ((arguments != null) && (arguments.length != 0)) { 
  199.             for (int i = 0; i < arguments.length; i++) { 
  200.                 sb.append(".").append(arguments[i]); 
  201.             } 
  202.         } 
  203.         return sb.toString(); 
  204.     } 

這里的方法攔截器主要是對(duì)你要攔截的類的方法進(jìn)行攔截,然后判斷該方法的類路徑+方法名稱+參數(shù)值組合的cache key在緩存cache中是否存在。如果存在就從緩存中取出該對(duì)象,轉(zhuǎn)換成我們要的返回類型。沒有的話就把該方法返回的對(duì)象添加到緩存中即可。值得主意的是當(dāng)前方法的參數(shù)和返回值的對(duì)象類型需要序列化。

我們需要在src目錄下添加applicationContext.xml完成對(duì)MethodCacheInterceptor攔截器的配置,該配置主意是注入我們的cache對(duì)象,哪個(gè)cache來管理對(duì)象緩存,然后哪些類、方法參與該攔截器的掃描。

添加配置如下:

 
 
  1.   
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.      
  9.      
  10.      
  11.  
  12.  
  13.  
  14.  
  15.      
  16.  
  17.  
  18.  
  19.  
  20.      
  21.      
  22.      
  23.                       
  24.      
  25.      
  26.          
  27.             com.hoo.rest.*RestService*\.*get.* 
  28.             com.hoo.rest.*RestService*\.*search.* 
  29.          
  30.      
  31.  
  32. 在ehcache.xml中添加如下cache配置 
  33.  
  34.         maxElementsInMemory="10000" 
  35.         eternal="false" 
  36.         overflowToDisk="true" 
  37.         timeToIdleSeconds="1800" 
  38.         timeToLiveSeconds="3600" 
  39.         memoryStoreEvictionPolicy="LFU" /> 

原文鏈接:http://www.cnblogs.com/hoojo/archive/2012/07/12/2587556.html


分享標(biāo)題:Spring中集成Ehcache使用頁面、對(duì)象緩存
URL網(wǎng)址:http://m.5511xx.com/article/cdhphpe.html