ehcache 原理缓存读不出来

缓存和ehcache_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
评价文档:
6页免费6页免费3页免费10页免费4页免费 6页1下载券4页免费3页免费4页免费9页免费
喜欢此文档的还喜欢6页免费21页免费12页1下载券23页1下载券19页2下载券
缓存和ehcache|缓​存​和​e​h​c​a​c​h​e
把文档贴到Blog、BBS或个人站等:
普通尺寸(450*500pix)
较大尺寸(630*500pix)
你可能喜欢精品:spring ehcache spring3 ehcache ehcache ehcache diskstore ehcache 使用 ..
扫扫二维码,随身浏览文档
手机或平板扫扫即可继续访问
EHCache技术文档缓存spring缓存
举报该文档为侵权文档。
举报该文档含有违规或不良信息。
反馈该文档无法正常浏览。
举报该文档为重复文档。
推荐理由:
将文档分享至:
分享完整地址
文档地址:
粘贴到BBS或博客
flash地址:
支持嵌入FLASH地址的网站使用
html代码:
&embed src='/DocinViewer-4.swf' width='100%' height='600' type=application/x-shockwave-flash ALLOWFULLSCREEN='true' ALLOWSCRIPTACCESS='always'&&/embed&
450px*300px480px*400px650px*490px
支持嵌入HTML代码的网站使用
您的内容已经提交成功
您所提交的内容需要审核后才能发布,请您等待!
3秒自动关闭窗口Hibernate使用EHcache二级缓存
- blue - 博客园
随笔 - 2, 文章 - 35, 评论 - 25, 引用 - 0
hibernate的session提供了一级缓存,每个session,对同一个id进行两次load,不会发送两条sql给数据库,但是session关闭的时候,一级缓存就失效了。
  二级缓存是SessionFactory级别的全局缓存,它底下可以使用不同的缓存类库,比如ehcache、oscache等,需要设置hibernate.cache.provider_class,我们用ehcache。   缓存可以简单的看成一个Map,通过key在缓存里面找value。
配置: Ehcache.xml <?xml version="1.0" encoding="UTF-8"?> <ehcache>  <diskStore path="硬盘目录"/>   <defaultCache    maxElementsInMemory="10000" <!-- 缓存最大数目 -->    eternal="false" <!-- 缓存是否持久 -->    overflowToDisk="true" <!-- 是否保存到磁盘,当系统当机时-->    timeToIdleSeconds="300" <!-- 当缓存闲置n秒后销毁 -->    timeToLiveSeconds="180" <!-- 当缓存存活n秒后销毁-->    diskPersistent="false"    diskExpiryThreadIntervalSeconds= "120"/> </ehcache>
defaultCache为默认的缓存策略,可以根据各个不同的实例单独制订缓存策略 如: &cache name="org.hibernate.cache.UpdateTimestampsCache" maxElementsInMemory="5000" eternal="true" overflowToDisk="true"/&
Hibernate配置文件中设置 如果不设置“查询缓存”,那么hibernate只会缓存使用load()方法获得的单个持久化对象,如果想缓存使用findall()、list()、Iterator()、createCriteria()、createQuery()等方法获得的数据结果集的话,就需要设置 hibernate.cache.use_query_cache true 才行 &prop key="hibernate.cache.use_query_cache"&true&/prop&
<!-- 设置Hibernate的缓存接口类,这个类在Hibernate包中 --> &prop key="hibernate.cache.provider_class"& org.hibernat.cache.EhCacheProvider &/prop&
&bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"& &property name="sessionFactory"& &ref bean="sessionFactory" /& &/property& &property name="cacheQueries"& &value&true&/value& &/property& &/bean& Hbm &cache usage="transactional|read-write|nonstrict-read-write|read-only" (1) /&
ehcache不支持transactional,其他三种可以支持。 read-only:无需修改, 那么就可以对其进行只读 缓存,注意,在此策略下,如果直接修改数据库,即使能够看到前台显示效果,但是将对象修改至cache中会报error,cache不会发生作用。另:删除记录会报错,因为不能在read-only模式的对象从cache中删除。 read-write:需要更新数据,那么使用读/写缓存 比较合适,前提:数据库不可以为serializable transaction isolation level(序列化事务隔离级别) nonstrict-read-write:只偶尔需要更新数据(也就是说,两个事务同时更新同一记录的情况很不常见),也不需要十分严格的事务隔离,那么比较适合使用非严格读/写缓存策略。
调试信息查看 调试时候使用log4j的log4j.logger.org.hibernate.cache=debug,更方便看到ehcache的操作过程,主要用于调试过程,实际应用发布时候,请注释掉,以免影响性能。 在log4j.properties里加上这句log4j.logger.org.hibernate.cache=debug Log信息如:
17:58:23,718 http-8080-Processor23 DEBUG NonstrictReadWriteCache:71 - Caching: com.maf.family.entity.Family#62
Criteria查询 Session s=HibernateSessionFactory.getSession(); Criteria c=s.createCriteria(Resources.class); c.setCacheable(true); //添加
SessionFactory也提供了移除缓存的方法 void evict(Class persistentClass) Evict all entries from the second-level cache. void evict(Class persistentClass, Serializable id) Evict an entry from the second-level cache. void evictCollection(String roleName) Evict all entries from the second-level cache. void evictCollection(String roleName, Serializable id) Evict an entry from the second-level cache. void evictQueries() Evict any query result sets cached in the default query cache region. void evictQueries(String cacheRegion) Evict any query result sets cached in the named query cache region.
但这样做很难维护Ehcache缓存之web应用实例
-------------
新增文件夹...
新增文件夹
(多个标签用逗号分隔)
Ehcache缓存之web应用实例
前面学习了缓存的基本配置和使用,下面继续学习如何缓存一个页面
我搭建的环境是 spring+freemarker+Maven& ,没有使用hibernate配置缓存 ,想先弄个简单的页面缓存看看
需要jar包:
&&&&&&& &dependency&
&&&&&&&&& &groupId&net.sf.ehcache&/groupId&
&&&&&&&&& &artifactId&ehcache-web&/artifactId&
&&&&&&&&& &version&2.0.4&/version&
&&&&&&& &/dependency&
可以加上这个仓库& https://oss.sonatype.org/content/groups/sourceforge/
我测试ehcache配置如下
&ehcache updateCheck="false" dynamicConfig="false"&
!-- Sets the path to the directory where cache .data files are created.
If the path is a Java System Property it is replaced by
its value in the running VM.
The following properties are translated:
user.home - User's home directory
user.dir - User's current working directory
java.io.tmpdir - Default temp file path --&
&diskStore path="d:\\ehcache\\tmpdir"/&
&cacheManagerEventListenerFactory class="" properties=""/&
&!--Default Cache configuration. These will applied to caches programmatically created through
the CacheManager.
The following attributes are required for defaultCache:
maxInMemory
- Sets the maximum number of objects that will be created in memory
- Sets whether elements are eternal. If eternal,
timeouts are ignored and the element
is never expired.
timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only used
if the element is not eternal. Idle time is now - last accessed time
timeToLiveSeconds - Sets the time to live for an element before it expires. Is only used
if the element is not eternal. TTL is now - creation time
overflowToDisk
- Sets whether elements can overflow to disk when the in-memory cache
has reached the maxInMemory limit.
&defaultCache
maxElementsInMemory="1000"
eternal="false"
timeToIdleSeconds="1200000"
timeToLiveSeconds="1200000"
overflowToDisk="true"
&cache name="icache-global"
maxElementsInMemory="1"
maxElementsOnDisk="1"
eternal="true"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
overflowToDisk="true"
&!-- 测试用 --&
&cache name="SimplePageCachingFilter"
maxElementsInMemory="10"
maxElementsOnDisk="10"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="100"
timeToLiveSeconds="30"
memoryStoreEvictionPolicy="LFU"
&cache name="SimplePageFragmentCachingFilter"
maxElementsInMemory="1"
maxElementsOnDisk="1"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU"
&/ehcache&
首先学习下缓存配置中几个重要的参数配置
&cache name="SimplePageCachingFilter"
maxElementsInMemory="10"& &&& //这个是表示SimplePageCachingFilter缓存在内存中的element数量
maxElementsOnDisk="10"&&& //这个是表示SimplePageCachingFilter缓存在磁盘中的element数量
eternal="false"&&&&& //说明该缓存会死亡
overflowToDisk="true"&& //设置是否溢出是是否存到磁盘上
timeToIdleSeconds="10"&&& //多长时间不访问该缓存,那么ehcache 就会清除该缓存.
timeToLiveSeconds="30"&&& //缓存的存活时间,从开始创建的时间算起.
memoryStoreEvictionPolicy="LFU"&& //缓存的清空策略
ehcache 中缓存的3 种清空策略:
1 FIFO ,first in first out ,这个是大家最熟的,先进先出,不多讲了
2 LFU , Less Frequently Used ,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的.如上面所讲,缓存的元素有一个hit 属性,hit 值最小的将会被清出缓存.
2 LRU ,Least Recently Used ,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存.
&缓存的其他知识可以去百度去,这里介绍缓存的存储方式和一些原理
下面是web.xml方面的配置
&!-- ehcache --&
&filter-name&SimplePageCachingFilter&/filter-name&
&filter-class&net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter
&/filter-class&
&!-- This is a filter chain. They are executed in the order below.
Do not change the order. --&
&filter-mapping&
&filter-name&SimplePageCachingFilter&/filter-name&
&url-pattern&*.do&/url-pattern&
&/filter-mapping&
注意: ehcache.xml文件中配置的缓存名称 必须和web.xml配置的缓存filter名字一致 不然会抛出找不到配置的异常 ;并且必须把ehcache.xml放在class根目录下。
接下来就是写一个Controller了
@Controller
public class EhcacheController extends BaseAction {
@RequestMapping(value = "ehcache/save.do" ,method=RequestMethod.GET)
public String index(Locale locale, Model model,HttpServletRequest request,
HttpServletResponse response) throws Exception{
daotie home ,the client locale is "+ locale.toString());
return "ehcache/show";
我写的是 spring的mvc实现,接下来我们就需要看ehcache/show.ftl页面看看是否用了缓存
你可以再访问一次后,里面修改show.ftl页面内容,会发现没有变化,等过了30秒(因为我在缓存中配置的SimplePageCachingFilter的缓存存活时间是30秒)后就变了,说明缓存起了作用了。
相关资讯  — 
相关文档  — 
发布时间: 08:31:01
同类热门经验
6845次浏览
3876次浏览
5760次浏览
5885次浏览
5670次浏览
2950次浏览
OPEN-OPEN, all rights reserved.8012人阅读
1.技术背景:
&& &系统缓存是位于应用程序与物理数据源之间,用于临时存放复制数据的内存区域,目的是为减少应用程序对物理数据源访问的次数,从而提高应用程序的运行性能。缓存设想内存是有限的,缓存的时效性也是有限的,所以可以设定内存数量的大小可以执行失效算法,可以在内存满了的情况下,按照最少访问等算法将缓存直接移除或切换到硬盘上。
&& &Ehcache从Hibernate发展而来,逐渐涵盖了Cache界的全部功能,是目前发展势头最好的一个项目,具有快速、简单、低消耗、扩展性强、支持对象或序列化缓存,支持缓存或元素的失效,提供LRU、LFU和FIFO缓存策略,支持内存缓存和硬盘缓存和分布式缓存机制等特点。其中Cache的存储方式为内存或磁盘(ps:无须担心容量问题)
2.EhCahe的类层次介绍:
&& &主要分为三层,最上层是CacheManager,它是操作Ehcache的入口。可以通过CacheManager.getInstance()获得一个单子的CacheManager,或者通过CacheManager的构造函数创建一个新的CacheManager。每个CacheManger都管理多个Cache。每个Cache都以一种类Hash的方式,关联多个Element。Element就是我们用于存放缓存内容的地方。
3.环境搭建:
&& &很简单只需要将ehcache-2.1.0-distribution.tar.gz和ehcache-web-2.0.2-distribution.tar.gz挤压的jar包放入WEB-INF/lib下。
&& &再创建一个重要的配置文件ehcache.xml,可以从ehcache组件包中拷贝一个,也可以自己建立一个,需要放到classpath下,一般放于/WEB-INF/classes/ehcache.xml;具体的配置文件可以网上搜一下
4.实际运用
&& &一个网站的首页估计是被访问次数最多的,我们可以考虑给首页做一个页面缓存;
&& &缓存策略:应该是某个固定时间之内不变的,比如说2分钟更新一次,以应用结构page-filter-action-service-dao-db为例。
&& &位置:页面缓存做到尽量靠近客户的地方,就是在page和filter之间,这样的优点就是第一个用户请求后,页面被缓存,第二个用户在请求,走到filter这个请求就结束了,需要在走到action-service-dao-db,好处当然是服务器压力大大降低和客户端页面响应速度加快。
&& &首页页面缓存存活时间定为2分钟,也就是参数timeToLiveSeconds(缓存的存活时间)应该设置为120,同时timeToIdleSeconds(多长时间不访问缓存,就清楚该缓存)最好也设为2分钟或者小于2分钟。

接着我们来看一下SimplePageCachingFilter 的配置,
&filter-name&indexCacheFilterfilter-name&
&filter-class&
net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter
&filter-class&
&filter-mapping&
&filter-name&indexCacheFilterfilter-name&
&url-pattern&*index.actionurl-pattern&
&filter-mapping&
将上述代码加入到web.xml,那么当打开首页时,你会发现2分钟才会有一堆sql语句出现在控制台,也可以调整为5分钟,总之一切尽在掌控之中。
当然,如果你像缓存首页的部分内容时,你需要使用SimplePageFragmentCachingFilter这个filter,我看一下:
&filter-name&indexCacheFilterfilter-name&
&filter-class&
net.sf.ehcache.constructs.web.filter.SimplePageFragmentCachingFilter
&filter-class&
&filter-mapping&
&filter-name&indexCacheFilterfilter-name&
&url-pattern&*/index_right.jsp&url-pattern&
&filter-mapping&如此我们将jsp页面通过jsp:include到其他页面,这样就做到了页面局部缓存的效果,这一点貌似没有oscache的tag好用。
此外cachefilter中还有一个特性,就是gzip,也就是缓存中的元素是被压缩过的,如果客户端浏览器支持压缩的话,filter会直接返回压缩过的流,这样节省了带宽,把解压的工作交给了客户端浏览即可,当然如果客户端不支持gzip,那么filter会把缓存的元素拿出来解压后在返回给客户端浏览器(大多数爬虫是不支持gzip的,所以filter也会解压后在返回流)。
总之,Ehcache是一个非常轻量级的缓存实现,而且从1.2之后支持了集群,而且是hibernate默认的缓存provider,本文主要介绍Ehcahe对页面缓存的支持,但是它的功能远不止如此,要用好缓存,对J2ee中缓存的原理、适用范围、适用场景等等都需要比较深刻的理解,这样才能用好用对缓存。
为了大家通过实际例子加深了解与场景运用,在奉献一个实例:
*在Spring中运用EhCache
&& &适用任意一个现有开源Cache Framework,要求可以Cache系统中service或者DAO层的get/find等方法返回结果,如果数据更新(适用了Create/update/delete),则刷新cache中相应的内容。
&& &根据需求,计划适用Spring AOP+enCache来实现这个功能,采用ehCache原因之一就是Spring提供了enCache的支持,至于为何仅仅支持ehcache而不支持oscache和jbosscache就无从得知了。
&& &AOP少不了拦截器,先创建一个实现了MethodInterceptor接口的拦截器,用来拦截Service/DAO的方法调用,拦截到方法后,搜索该方法的结果在cache中是否存在,如果存在,返回cache中结果,如果不存在返回数据库查询结果,并将结果返回到缓存。
public class MethodCacheInterceptor implements MethodInterceptor, InitializingBean
private static final Log logger = LogFactory.getLog(MethodCacheInterceptor.class);
public void setCache(Cache cache) {
this.cache =
public MethodCacheInterceptor() {
* 拦截Service/DAO 的方法,并查找该结果是否存在,如果存在就返回cache 中的值,
* 否则,返回数据库查询结果,并将查询结果放入cache
public Object invoke(MethodInvocation invocation) throws Throwable {
String targetName = invocation.getThis().getClass().getName();
String methodName = invocation.getMethod().getName();
Object[] arguments = invocation.getArguments();
logger.debug(&Find object from cache is & + cache.getName());
String cacheKey = getCacheKey(targetName, methodName, arguments);
Element element = cache.get(cacheKey);
Page 13 of 26
if (element == null) {
logger.debug(&Hold up method , Get method result and create cache........!&);
result = invocation.proceed();
element = new Element(cacheKey, (Serializable) result);
cache.put(element);
return element.getValue();
* 获得cache key 的方法,cache key 是Cache 中一个Element 的唯一标识
* cache key 包括包名+类名+方法名,如com.co.cache.service.UserServiceImpl.getAllUser
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. i++) {
sb.append(&.&).append(arguments[i]);
return sb.toString();
* implement InitializingBean,检查cache 是否为空
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache, &Need a cache. Please use setCache(Cache) create it.&);
上面的代码可以看到,在方法invoke中,完成了搜索cache/新建cache的功能
随后,再建立一个拦截器MethodCacheAfterAdvice,作用是在用户进行create/update/delete操作时来刷新、remove相关cache内容,这个拦截器需要实现AfterRetruningAdvice接口,将会在所拦截的方法执行后执行在afterReturning(object arg0,Method arg1,Object[] arg2,object arg3)方法中所预定的操作
public class MethodCacheAfterAdvice implements AfterReturningAdvice, InitializingBean
private static final Log logger = LogFactory.getLog(MethodCacheAfterAdvice.class);
Page 15 of 26
public void setCache(Cache cache) {
this.cache =
public MethodCacheAfterAdvice() {
public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws
Throwable {
String className = arg3.getClass().getName();
List list = cache.getKeys();
for(int i = 0;i&list.size();i++){
String cacheKey = String.valueOf(list.get(i));
if(cacheKey.startsWith(className)){
cache.remove(cacheKey);
logger.debug(&remove cache & + cacheKey);
public void afterPropertiesSet() throws Exception {
Assert.notNull(cache, &Need a cache. Please use setCache(Cache) create it.&);
}该方法获取目标class的全名,如:com.co.cache.test.TestServiceImpl,然后循环cache的key list,刷新/remove cache中所有和该class相关的element。
接着就是配置encache的属性,如最大缓存数量、cache刷新的时间等等。
&diskStore path=&c:\\myapp\\cache&/&
&defaultCache
maxElementsInMemory=&1000&
eternal=&false&
timeToIdleSeconds=&120&
timeToLiveSeconds=&120&
overflowToDisk=&true&
&cache name=&DEFAULT_CACHE&
maxElementsInMemory=&10000&
eternal=&false&
timeToIdleSeconds=&300000&
timeToLiveSeconds=&600000&
overflowToDisk=&true&
&/ehcache&
这里需要注意的是defaultCache定义了一个默认的cache,这个Cache不能删除,否则会抛出No default cache is configured异常。另外由于使用拦截器来刷新Cache内容,因此在定义cache生命周期时可以定义较大的数值,timeToIdleSeconds=&&,timeToLiveSeconds=&6000000&,好像还不够大?
然后再将Cache和两个拦截器配置到Spring的配置文件cache.xml中即可,需要创建两个“切入点”,分别用于拦截不同方法名的方法。在配置application.xml并且导入cache.xml。这样一个简单的Spring+Encache框架就搭建完成。
由于时间关系就介绍到这里,以后有机会还会介绍Ehcache在分布式集群系统中的使用,谢谢大家。
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
访问:132428次
积分:2218
积分:2218
排名:第6456名
原创:77篇
转载:13篇
评论:102条
(8)(1)(1)(3)(1)(2)(3)(2)(3)(7)(4)(5)(11)(2)(1)(5)(8)(3)(5)(1)(5)(7)(4)(1)(1)

我要回帖

更多关于 ehcache 原理 的文章

 

随机推荐