<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    隨筆-57  評論-117  文章-1  trackbacks-0

    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基本用法

    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();

     

    三、頁面緩存

    頁面緩存主要用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()%>如果時間是變動的,則表示該頁面沒有被緩存或是緩存已經過期,否則則是在緩存狀態了。

     

    四、對象緩存

    對象緩存就是將查詢的數據,添加到緩存中,下次再次查詢的時候直接從緩存中獲取,而不去數據庫中查詢。

    對象緩存一般是針對方法、類而來的,結合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" />


    作者:hoojo
    出處:
    blog:http://blog.csdn.net/IBM_hoojo
             http://hoojo.cnblogs.com
    本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。


    版權所有,轉載請注明出處 本文出自:
    分享道版權所有,歡迎轉載,轉載請注明出處,謝謝
    posted on 2012-07-12 10:15 hoojo 閱讀(5010) 評論(0)  編輯  收藏 所屬分類: FrameWork IntegrationJavaEEOthersSpring
    主站蜘蛛池模板: 亚洲一区二区三区丝袜| 亚洲精品无码久久毛片| 国产曰批免费视频播放免费s| 一级毛片成人免费看免费不卡| 十八禁在线观看视频播放免费| 精品熟女少妇aⅴ免费久久| 一级人做人爰a全过程免费视频| 美女被免费视频网站a| 三年片在线观看免费观看大全中国| 理论秋霞在线看免费| 国产成人亚洲精品91专区高清| 免费无码国产在线观国内自拍中文字幕 | 无码视频免费一区二三区| 又粗又大又黑又长的免费视频 | 小说专区亚洲春色校园| 黄页网址大全免费观看12网站| 免费无码又爽又黄又刺激网站| 黄色网址免费在线观看| 国产成人免费视频| 精品国产污污免费网站aⅴ | 久久九九全国免费| 成人免费大片免费观看网站| 成人免费视频软件网站| 免费观看四虎精品国产永久| 爱情岛论坛网亚洲品质自拍| 久久亚洲国产精品五月天| 亚洲第一二三四区| 亚洲人成色99999在线观看| 国产av无码专区亚洲av毛片搜| 国产免费一区二区三区免费视频| 免费毛片在线看不用播放器| 18女人腿打开无遮掩免费| 成人免费无码大片a毛片软件| 免费中文字幕在线| 亚洲Av无码专区国产乱码DVD| 666精品国产精品亚洲| 亚洲娇小性色xxxx| 全部一级一级毛片免费看| 免费av一区二区三区| AV片在线观看免费| av在线亚洲欧洲日产一区二区|