EhCache 整合Spring 使用页面缓存

      Ehcache对质页面、对象、数据缓存,同时支持集群/分布式缓存。整合Spring、Hibernate也非常的简单,spring对Ehcache的支持也非常好。EHCache支持内存和磁盘的缓存,支持LRU、LFU和FIFO多种淘汰算法,支持分布式的Cache,可以作为Hibernate的缓存插件。同时它也能提供基于Filter的Cache,该Filter可以缓存响应的内容并采用Gzip压缩提高响应速度。

下面配置EhCache的页面缓存

一、依赖jar包

ehcache-core-2.5.2.jar

ehcache-web-2.0.4.jar 

其它spring等相关jar包

二、加入ehcache.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<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="3" 
        timeToLiveSeconds="6"
        memoryStoreEvictionPolicy="LFU" />
 
</ehcache>

 三、重新实现SimplePageCachingFilter类,SimplePageCachingFilter类也可以不重现实现,也能达到缓存效果,这里根据实现需求,进行重新实现

package com.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.web.filter.SimplePageCachingFilter;

import org.apache.cxf.common.util.StringUtils;

/**
 * EhCache  页面缓存过滤器
 *
 */
public class PageCachingFilter extends SimplePageCachingFilter {

	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) {
		try {
			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;
					}
				}
			}
			if (flag) {// 包含我们指定要缓存的url 就缓存该页面,否则执行正常的页面转向
				String query = request.getQueryString();
				if (query != null) {
					query = "?" + query;
					url = url + query;
				}
				System.out.println("当前请求被缓存:" + url);
				super.doFilter(request, response, chain);
			} else {
				chain.doFilter(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("rawtypes")
	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;
	}

	/** 兼容ie6/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加入配置

<!-- EhCache页面缓存 -->
<filter>
    <filter-name>PageCachingFilter</filter-name>
    <filter-class>com.cache.PageCachingFilter</filter-class>
    <init-param>
        <param-name>patterns</param-name>
        <!-- 配置你需要缓存的url -->
        <param-value>/pageCache.jsp</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>PageCachingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

 五、编辑测试页面pageCache.jsp

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试EhCache页面缓存</title>
</head>
<body>
测试EhCache页面缓存
<%  
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    out.print(format.format(new Date()));  
    System.out.println(System.currentTimeMillis());  
%>  
</body>
</html>

猜你喜欢

转载自tzz6.iteye.com/blog/2256597