一、对象缓存
加入ehcache jar (不使用缓存页面只需要这个jar)
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.8.3</version>
</dependency>
1.新建一个CacheManager对象
CacheManager manager= CacheManager.getInstance();
或manager= CacheManager.newInstance("/config/ehcache.xml");
2.获得Cache
Cache cache = manager.getCache(MY_CACHE);
或者new一个cache。
Cache cache = manager.getCache(MY_CACHE);
if (cache == null) {
synchronized(MyCache.class){
cache = manager.getCache(MY_CACHE);
if (cache == null) {
cache = new Cache(new CacheConfiguration(REQUEST_INFO, 100)
.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO)
.eternal(false)
.timeToLiveSeconds(30)
.timeToIdleSeconds(30)
.diskExpiryThreadIntervalSeconds(0)
.persistence(new PersistenceConfiguration()
.strategy(Strategy.LOCALTEMPSWAP)));
manager.addCache(cache);
}
}
}
3.使用cache
获得缓存数据
Element element = cache.get(key);
element.getObjectValue();
数据存入缓存
Element element = new Element(key, value);
cache.put(element);
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"/>
<!--
配置自定义缓存
maxEntriesLocalHeap="10" //堆内存中最大缓存对象数,0没有限制
maxElementsInMemory:缓存中允许创建的最大对象数
eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。
timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,
两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,
如果该值是 0 就意味着元素可以停顿无穷长的时间。
timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,
这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。
overflowToDisk:内存不足时,是否启用磁盘缓存。
memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。
-->
<cache name="CachePageCachingFilter"
maxEntriesLocalHeap="100"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="3600">
<persistence strategy="localTempSwap"/>
</cache>
<cache name="my_cache1"
eternal="true"
maxEntriesLocalHeap="200"
memoryStoreEvictionPolicy="LFU">
</cache>
<cache name="my_cache2"
eternal="true"
maxEntriesLocalHeap="1000"
memoryStoreEvictionPolicy="LFU">
</cache>
<cache name="my_cache3"
eternal="false"
maxEntriesLocalHeap="100"
timeToIdleSeconds="30"
timeToLiveSeconds="30"
memoryStoreEvictionPolicy="FIFO">
</cache>
</ehcache>
二、页面缓存
默认配置不需要编写代码,只需要配置一下即可。
加入
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-web</artifactId>
<version>2.0.4</version>
</dependency>
web.xml中加入filter
<filter>
<filter-name>CachePageCachingFilter</filter-name>
<filter-class>net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter</filter-class>
<init-param>
<param-name>cacheName</param-name>
<param-value>CachePageCachingFilter</param-value> 指向上面ehcache.xml文件中的一个cache
</init-param>
</filter>
<filter-mapping>
<filter-name>CachePageCachingFilter</filter-name>
<url-pattern>index.home</url-pattern>
</filter-mapping>
配置完之后会缓存index.home请求的结果,下次请求index.home会直接使用缓存数据。
或者继承net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter 重写指定方法
web.xml
<filter>
<filter-name>CachePageCachingFilter</filter-name>
<filter-class>com.yym.filter.EhcachePageFilter</filter-class>
<init-param>
<param-name>patterns</param-name>
<param-value>index.home</param-value>
</init-param>
<init-param>
<param-name>cacheName</param-name>
<param-value>CachePageCachingFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CachePageCachingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
EhcachePageFilter.class
package com.yym.filter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* ehcache 页面缓存,缓存指定的url地址
* @author yym
*
*/
public class EhcachePageFilter extends SimplePageCachingFilter {
private final static Log LOG = LogFactory.getLog(EhcachePageFilter.class);
private final static String FILTER_URL_PATTERNS = "patterns";
private static List<Pattern> patterns;
private static int token = 0;
public void init() {
String cacheUrlString = filterConfig.getInitParameter(FILTER_URL_PATTERNS);
String[] cacheURLs = StringUtils.split(cacheUrlString, ";");
if (ArrayUtils.isNotEmpty(cacheURLs)) {
patterns = new ArrayList<Pattern>();
for (String string : cacheURLs) {
patterns.add(Pattern.compile("\\S*"+string.replace("*", "\\S*")));
}
}
token = 1;
}
@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws AlreadyGzippedException, AlreadyCommittedException, FilterNonReentrantException, LockTimeoutException, Exception {
if (CollectionUtils.isEmpty(patterns)) {
if (token == 0) {
init();
}
}
String url = request.getRequestURI();
boolean flag = false;
if (CollectionUtils.isNotEmpty(patterns)) {
for (Pattern pattern : patterns) {
if (pattern.matcher(url).matches()) {
flag = true;
break;
}
}
}
if (flag) {
String query = request.getQueryString();
if (query != null) {
query = "?" + query;
LOG.info("当前请求被缓存:" + url + query);
}else {
LOG.info("当前请求被缓存:" + url);
}
super.doFilter(request, response, chain);
} else {
chain.doFilter(request, response);
}
}
@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;
}
@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;
}
}