使用Ehcache給頁面作緩存

使用Ehcache給頁面作緩存 java

 

 

.準備相關文件 web

        

         1.下載 JAR 算法

 

         使用Ehcache作頁面的緩存,因此只須要下載 ehcache-core和ehcache-web模塊 apache

         ehcache 下載地址:http://ehcache.org/modules 緩存

        

         2.jar複製到lib文件夾 session

        

         ehcache-core-XXX.jar app

         ehcache-web-XXX.jar 主要針對頁面緩存 jsp

 

         3.複製配置文件 ide

        

         複製 ehcache.xml  到 src 目錄。保證編譯後會複製到web-inf/classes下面 測試

        

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">

    <!-- 緩存文件存放目錄 :默認為這個路徑,也能夠自定義路徑-->
    <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 指向一個cachingFiter,默認使用 SimplePageCachingFilter就夠用了。
    -->
    <cache name="SimplePageCachingFilter" 
           maxElementsInMemory="10000" 
           eternal="false"
           overflowToDisk="false" 
           timeToIdleSeconds="900" 
           timeToLiveSeconds="1800"
           memoryStoreEvictionPolicy="LFU" />
 
</ehcache>



 

二.寫FILTER對路徑進行攔截。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.yhl.jfinal_helloword.cache;

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;

/**
 * 頁面緩存過濾器
 * @version 1.0
 * @author YHL
 */
public class PageEhCacheFilter extends SimplePageCachingFilter{
    private final static Logger log = Logger.getLogger(PageEhCacheFilter.class);
    
    private final static String FILTER_URL_PATTERNS = "patterns"; //WEB.XML中配置要過濾的地址
    private static String[] cacheURLs;
    private static boolean cache_index=false;

    private void init() throws CacheException {
        String patterns = filterConfig.getInitParameter(FILTER_URL_PATTERNS);
        cacheURLs = StringUtils.split(patterns, ",");
    }

    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();
        String url = request.getServletPath();
        boolean flag = false;
        if (cacheURLs != null && cacheURLs.length > 0) {
            for (String cacheURL : cacheURLs) {
                if (url.startsWith(cacheURL.trim())) {
                    flag = true;
                    break;
                }
            }
        }
//      
        // 若是包含咱們要緩存的url 就緩存該頁面,不然執行正常的頁面轉向
        if (flag) {
            String query = request.getQueryString();
            if ( !StringUtils.isBlank( query )) {
                query = "?" + query;
            }
            log.info("當前請求被緩存:" + url + (!StringUtils.isBlank(query)&& !query.equalsIgnoreCase("null")?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;
    }

    /**
     * 兼容ie六、7 使用gzip壓縮
     */
    @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

            注意:必定要將ehcachefilter 配置在 其餘 filter以前。

                         還有注意filter-class的包名和文件名。

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
   
    
    <!-- 緩存、gzip壓縮核心過濾器 -->
    <filter>
        <filter-name>PageEhCacheFilter</filter-name>
        <filter-class>com.yhl.jfinal_helloword.cache.PageEhCacheFilter</filter-class>
        <init-param>
            <description>使用絕對路徑進行匹配。url.starWith(緩存路徑)</description>
            <param-name>patterns</param-name>
            <param-value>/hello,/index.jsp</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>PageEhCacheFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    
     <filter>
        <filter-name>jfinal</filter-name>
        <filter-class>com.jfinal.core.JFinalFilter</filter-class>
        <init-param>
            <param-name>configClass</param-name>
            <param-value>com.yhl.jfinal_helloword.config.DemoConfig</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>jfinal</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
    
    
    <!-- 緩存配置結束 -->
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>




.測試

           若是是動態頁面,能夠根據頁面變化來判斷是否緩存。

            也能夠在jsp中添加<%=new Date()%> 經過刷新頁面,看時間的變化進行判斷。

相關文章
相關標籤/搜索