Ehcache 整合Spring 使用頁面、對象緩存


Ehcache在很多項目中都出現過,用法也比較簡單。一般的加些配置就可以了,而且Ehcache可以對頁面、對象、數據進行緩存,同時支持集羣/分佈式緩存。如果整合Spring、Hibernate也非常的簡單,Spring對Ehcache的支持也非常好。EHCache支持內存和磁盤的緩存,支持LRU、LFU和FIFO多種淘汰算法,支持分佈式的Cache,可以作爲Hibernate的緩存插件。同時它也能提供基於Filter的Cache,該Filter可以緩存響應的內容並採用Gzip壓縮提高響應速度。

Email:[email protected]

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 [email protected]
 * @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 [email protected]
 * @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" />

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章