- 浏览: 920335 次
- 性别:
- 来自: 重庆
文章分类
- 全部博客 (453)
- Windows phone 7 (0)
- Andriod (47)
- iPhone (1)
- Web (30)
- J2EE (34)
- stucts 2学习笔记 (34)
- 开发项目 (3)
- spring学习笔记 (24)
- EJB学习笔记 (6)
- Hibernate学习笔记 (15)
- JPA学习笔记 (8)
- Jsp (11)
- ajax (7)
- 异常收集模块 (1)
- jquery (2)
- phoneGap (2)
- jquery Mobile (0)
- java面试总结 (5)
- Object-C (0)
- javascript (6)
- Eclipse (5)
- 支付集成 (2)
- Weblogic (1)
- Dubbox (5)
- Redis (10)
- linux (21)
- Codis (2)
- React Native (0)
- Mysql (6)
- Docker (3)
- 自动化部署 (1)
- 项目Bug管理平台 (2)
- 负载均衡 (1)
- Mycat (2)
- Java基础知识 (16)
- 数据库 (7)
- Maven (17)
- Kafka (21)
- logs (2)
- 大并发 (2)
- 消息中间件 (2)
- 分布式锁 (3)
- 算法 (4)
- 数字证书原理,公钥私钥 (0)
- 数字证书原理 (1)
- 公钥私钥 (1)
- zookeeper (4)
- Hbase (9)
- Hadoop (2)
- storm (2)
- 通信协议 (1)
- Hive (3)
- git (1)
- JVM (2)
- 大数据相关算法 (1)
- idea (5)
- 将博客搬至CSDN (1)
- 设计模式 (2)
- 表达式 (1)
- 代码审查工具 (0)
- 开源项目 (1)
- PyCharm (0)
- python (6)
- Kubernetes (1)
- swagger (1)
- Maven中mirrors和repository的关系 (0)
- RabbitMQ (3)
- redisson (1)
- k8s (2)
- Mac (1)
最新评论
-
misisipi101:
假设库已经分为32个,那么要扩展到64个,怎样做呢
订单分库分表实践总结以及关键步骤 -
mfkxk298:
简单明了的例子,解决了问题,谢谢啦!
关于ListView中notifyDataSetChanged()刷新数据不更新原因 -
whbwang:
" target="_blank" ...
java web开发 高并发处理 -
suguoqian:
...
java web开发 高并发处理 -
xiangnanyujing:
Dubbox+Redis3.0+Spring+Hibernate+zookeeper实现消息推送核心搭建
Ehcache 整合Spring 使用页面、对象缓存
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" />
转载:http://jayeye.iteye.com/blog/1988123
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" />
转载:http://jayeye.iteye.com/blog/1988123
发表评论
-
CDN加速WordPress触发CORS导致跨域加载失败
2018-04-09 17:36 1511这两天折腾CDN加速来提升自己博客的访问速度,用的阿里云C ... -
轻松看懂Java字节码
2018-04-09 10:28 583计算机只认识0和1。这意味着任何语言编写的程序最终都 ... -
happens-before俗解
2018-04-09 10:03 557学习Java并发,到后面总会接触到happens-befor ... -
位与&,位或|,位异或^运算
2018-04-04 17:25 595一.按位与运算符 参加运算的两个数据,按二进制位进行位与 ... -
Java中>>、>>>、<<
2018-04-04 14:47 400定义: 右移动>>:带符号右移。正数右移高位 ... -
在Java中谈尾递归--尾递归和垃圾回收的比较
2017-08-29 17:49 430转载请注明:博客园- ... -
PV模型
2017-02-05 18:05 684你想建设一个能承受500万PV/每天的网站吗? 500万PV ... -
hotspot的垃圾回收策略,设置和调优
2017-01-11 18:48 1846我们都知道JVM内存由几个部分组成: Java栈、程序计数器 ... -
两点距离计算
2016-11-05 18:03 518public class DistanceUtil { pr ... -
protobuf对象序列化问题一
2016-06-15 21:07 2748今天在项目中遇到一个奇葩问题。问题描述:项目基于dubbo服务 ... -
Protostuff对象序列化工具
2016-06-08 09:53 1760VO.java import java.io.Serial ... -
高性能序列化、反序列化protostuff 使用
2016-06-07 16:45 29991、引用jar包: pom.xml: <!-- p ... -
App开发一些总结
2016-04-05 17:48 2552架构因人而异,不同的架构师大多会有不同的看法;架构也因项目 ... -
解决fastjson内存对象相互应用导入json字符串出现错误问题
2016-04-05 17:48 1374日常在使用FastJson的时候可能很少会 ... -
分布式配置统一管理平台-Windows
2016-02-02 14:10 2679这里主要使用到disconf分布式配置管理平台 支持wind ... -
Codis使用入门
2016-01-15 16:35 1682首先严重吐槽 在使用Coids遇到无数坑 坑 坑 ... ... -
高可用消息队列框架ZBUS
2016-01-13 10:47 5887我们在日常开发中可以需要用到消息队列 当然我们完全可以自己 ... -
Java调用bat文件和exe文件
2016-01-12 11:09 918public static void main(String ... -
实现消息推送核心搭建(升级版)
2016-01-08 15:43 1679前面已经实现了第一版 ... -
Dubbox+Redis3.0+Spring+Hibernate+zookeeper实现消息推送核心搭建
2015-12-30 15:55 10495这里在开始搭建环境之前请搭建先熟悉了解Dubbox、Red ...
相关推荐
NULL 博文链接:https://bijian1013.iteye.com/blog/2263270
以java配置类方式 整合EhCache来实现页面整体缓存及页面局部缓存。详情见博客http://blog.csdn.net/poorCoder_/article/details/56483954
配置ehcache缓存,存储内存的设置,与spring 的整合等
缓存可以提高查询数据性能, 对同一批数据进行多次查询时, 第一次查询走数据库, 查询数据后,将数据保存在内存中,第二次以后查询 可以直接从内存获取数据,而不需要 和数据库进行交互。
1.通过google ehcache-spring-annotatios.jar自动注解方式实现整合Spring+Ehcache。 2.Action里通过struts2-spring-plugin.jar插件自动根据名字注入。 3.Ajax无刷新异步调用Struts2,返回Json数据,以用户注册为例。...
当我们不指定具体其他第三方实现的时候,Spring Boot的Cache模块会...而实际生产使用的时候,因为我们可能需要更多其他特性,往往就会采用其他缓存框架,所以接下来我们会分几篇分别介绍几个常用优秀缓存的整合与使用。
在一些要求高一致性(任何数据变化都能及时的被查询到)的系统和应用中,就不能再使用EhCache来解决了,这个时候使用集中式缓存是个不错的选择,因此本文将介绍如何在Spring Boot的缓存支持中使用Redis进行数据缓存...
Spring4.1+ehcache2.10.2实现缓存功能!
spring整合了ehcache,实现了缓存功能。附带读取properties文件信息功能。
Spring Boot中使用EhCache实现缓存支持,介绍整合方法和配置
SpringBoo2.x整合Ehcache3.x作为缓存底层存储。
本文先通过Ehcache独立应用的范例来介绍它的基本使用方法,然后再介绍与Spring整合的方法。
代码内含BoneCp连接池和注解缓存。没有提供Spring的jar包。只要加入Spring的包就可以使用。或者只需要BoneCP和注解缓存的可以直接到lib里拿jar包。
使用springboot 集成ehcache,里面附带数据库建库脚本,controller,service以及对ehcache集成,操作的详细样例,使用spring注解形式。
这是一个spring整合ehcache的完整用例,导入包后直接可以运行。ehcache.jar要导入1.2以上的,否则会报错。
1、springboot 整合ehcache+redis 通过配置文件application.yml切换缓存类型 2、ehcache 、redis 通过缓存管理器管理 3、可分别设置缓存的过期时间 ehcache :添加依赖 pom.xml 2、添加配置文件ehcache.xml 3、添加...
自己项目的开发包集合,其中包括:缓存处理ehcache相关jar,spring MVC4.0 jar,ehcache依赖jar,以及其他jar(图像处理thumbnailator-0.4.2),包虽然不是很新但可用。实际使用时找包较为麻烦,现在整理出来,希望...