ehcache cachemanager到达有效期之后内存中的cache会消失吗

Ehcache 中ehcache.xml 详解和示例 &ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"&
&diskStore path=".io.tmpdir"/&
Mandatory Default Cache configuration. These settings will be applied to caches
created programmtically using CacheManager.add(String cacheName)
name:缓存名称。
maxElementsInMemory:缓存最大个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
maxElementsOnDisk:硬盘最大缓存个数。
diskPersistent:是否缓存重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
&defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk=""
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"
&/ehcache&
---------------------------------------------------------------------------------------------------------------------配置说明:diskStore:配置DiskStore,当需要使用磁盘保存的时候,需要对象实现序列化
属性:path 位置,如user.home,user.dir,java.io.tmpdir defaultCache: 默认缓存配置
必须属性:
name:设置缓存的名称,用于标志缓存,惟一
maxElementsInMemory:在内存中最大的对象数量
maxElementsOnDisk:在DiskStore中的最大对象数量,如为0,则没有限制
eternal:设置元素是否永久的,如果为永久,则timeout忽略
overflowToDisk:是否当memory中的数量达到限制后,保存到Disk
可选的属性:
timeToIdleSeconds:设置元素过期前的空闲时间
timeToLiveSeconds:设置元素过期前的活动时间
diskPersistent:是否disk store在虚拟机启动时持久化。默认为false
diskExpiryThreadIntervalSeconds:运行disk终结线程的时间,默认为120秒
memoryStoreEvictionPolicy:策略关于Eviction 缓存子元素:
cacheEventListenerFactory:注册相应的的缓存监听类,用于处理缓存事件,如put,remove,,和expire
bootstrapCacheLoaderFactory:指定相应的BootstrapCacheLoader,用于在初始化缓存,以及自动设置。 --------------------------------------------------------------------------------------------------------------------- 在高并发量,高性能的应用系统时,缓存Cache起到了非常重要的作用。本文主要介绍EHCache的使用,以及使用EHCache的实践经验。笔者使用过多种基于Java的开源Cache组件,其中包括OSCache、JBossCache、EHCache。OSCache功能强大,使用灵活,可用于对象缓存、Filter缓存以及在JSP中直接使用cache标签。笔者在最近的使用过程中发现,在并发量较高时,OSCache会出现线程阻塞和数据错误,通过分析源发现是其内部实现的缺陷。JBossCache最大的优点是支持基于对象属性的集群同步,不过JBossCache的配置使用都较复杂,在并发量较高的情况下,对象属性数据在集群中同步也会加大系统的开销。以上两种Cache本文仅作简单介绍,不做深入探讨。EHCache是来自sourcege(http://ehcache.sourcege.net/)的开源,也是纯Java实现的简单、快速的Cache组件。EHCache支持内存和磁盘的缓存,支持LRU、LFU和FIFO多种淘汰算法,支持分布式的Cache,可以作为Hibernate的缓存插件。同时它也能提供基于Filter的Cache,该Filter可以缓存响应的内容并采用Gzip压缩提高响应速度。? EHCache API的基本用法首先介绍CacheManager类。它主要负责读取配置文件,默认读取CLASSPATH下的ehcache.xml,根据配置文件创建并管理Cache对象。// 使用默认配置文件创建CacheManagerCacheManager manager = CacheManager.create();// 通过manager可以生成指定名称的Cache对象Cache cache = cache = manager.getCache("demoCache");// 使用manager移除指定名称的Cache对象manager.removeCache("demoCache");可以通过调用manager.removalAll()来移除所有的Cache。通过调用manager的shutdown()方法可以关闭CacheManager。有了Cache对象之后就可以进行一些基本的Cache操作,例如://往cache中添加元素Element element = new Element("key", "value");cache.put(element);//从cache中取回元素Element element = cache.get("key");element.getValue();//从Cache中移除一个元素cache.remove("key");可以直接使用上面的API进行数据对象的缓存,这里需要注意的是对于缓存的对象都是必须可序列化的。在下面的篇幅中笔者还会介绍EHCache和Spring、Hibernate的整合使用。? 配置文件配置文件ehcache.xml中命名为demoCache的缓存配置:&cache name="demoCache"maxElementsInMemory="10000"eternal="false"overflowToDisk="true"timeToIdleSeconds="300"timeToLiveSeconds="600"memoryStoreEvictionPolicy="LFU" /&各配置参数的含义:maxElementsInMemory:缓存中允许创建的最大对象数eternal:缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期。timeToIdleSeconds:缓存数据的钝化时间,也就是在一个元素消亡之前,两次访问时间的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是 0 就意味着元素可以停顿无穷长的时间。timeToLiveSeconds:缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值,这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间。overflowToDisk:内存不足时,是否启用磁盘缓存。memoryStoreEvictionPolicy:缓存满了之后的淘汰算法。LRU和FIFO算法这里就不做介绍。LFU算法直接淘汰使用比较少的对象,在内存保留的都是一些经常访问的对象。对于大部分网站项目,该算法比较适用。如果应用需要配置多个不同命名并采用不同参数的Cache,可以相应修改配置文件,增加需要的Cache配置即可。? 利用Spring APO整合EHCache首先,在CLASSPATH下面放置ehcache.xml配置文件。在Spring的配置文件中先添加如下cacheManager配置:&bean id="cacheManager"class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"&&/bean&配置demoCache:&bean id="demoCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean"&&property name="cacheManager" ref="cacheManager" /&&property name="cacheName"&&value&demoCache&/value&&/property&&/bean&接下来,写一个实现org.aopalliance.intercept.MethodInterceptor接口的拦截器类。有了拦截器就可以有选择性的配置想要缓存的 bean 方法。如果被调用的方法配置为可缓存,拦截器将为该方法生成 cache key 并检查该方法返回的结果是否已缓存。如果已缓存,就返回缓存的结果,否则再次执行被拦截的方法,并缓存结果供下次调用。具体代码如下:public class MethodCacheInterceptor implements MethodInterceptor,InitializingBean {private Cpublic void setCache(Cache cache) {this.cache =}public void afterPropertiesSet() throws Exception {Assert.notNull(cache,"A cache is required. Use setCache(Cache) to provide class="com.xieg.utils.interceptor.MethodCacheInterceptor"&&property name="cache"&&ref local="demoCache" /&&/property&&/bean&&bean id="methodCachePointCut" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor"&&property name="advice"&&ref local="methodCacheInterceptor" /&&/property&&property name="patterns"&&list&&value&.*myMethod&/value&&/list&&/property&&/bean&&bean id="myServiceBean"class="com.xiebing.ehcache.spring.MyServiceBean"&&/bean&&bean id="myService" class="org.springframework.aop.framework.ProxyFactoryBean"&&property name="target"&&ref local="myServiceBean" /&&/property&&property name="interceptorNames"&&list&&value&methodCachePointCut&/value&&/list&&/property&&/bean&其中myServiceBean是实现了业务逻辑的Bean,里面的方法myMethod()的返回结果需要被缓存。这样每次对myServiceBean的myMethod()方法进行调用,都会首先从缓存中查找,其次才会查询。使用AOP的方式极大地提高了系统的灵活性,通过修改配置文件就可以实现对方法结果的缓存,所有的对Cache的操作都封装在了拦截器的实现中。? CachingFilter功能使用Spring的AOP进行整合,可以灵活的对方法的的返回结果对象进行缓存。CachingFilter功能可以对HTTP响应的内容进行缓存。这种方式缓存数据的粒度比较粗,例如缓存整张页面。它的优点是使用简单、效率高,缺点是不够灵活,可重用程度不高。EHCache使用SimplePageCachingFilter类实现Filter缓存。该类继承自CachingFilter,有默认产生cache key的calculateKey()方法,该方法使用HTTP请求的URI和查询条件来组成key。也可以自己实现一个Filter,同样继承CachingFilter类,然后覆写calculateKey()方法,生成自定义的key。在笔者参与的项目中很多页面都使用AJAX,为保证JS请求的数据不被缓存,每次请求都会带有一个随机数参数i。如果使用SimplePageCachingFilter,那么每次生成的key都不一样,缓存就没有意义了。这种情况下,我们就会覆写calculateKey()方法。要使用SimplePageCachingFilter,首先在配置文件ehcache.xml中,增加下面的配置:&cache name="SimplePageCachingFilter" maxElementsInMemory="10000" eternal="false"overflowToDisk="false" timeToIdleSeconds="300" timeToLiveSeconds="600"memoryStoreEvictionPolicy="LFU" /&其中name属性必须为SimplePageCachingFilter,修改web.xml文件,增加一个Filter的配置:&filter&&filter-name&SimplePageCachingFilter&/filter-name&&filter-class&net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter&/filter-class&&/filter&&filter-mapping&&filter-name&SimplePageCachingFilter&/filter-name&&url-pattern&/test.jsp&/url-pattern&&/filter-mapping&下面我们写一个简单的test.jsp文件进行测试,缓存后的页面每次刷新,在600秒内显示的时间都不会发生变化的。代码如下:&%out.println(new Date());%&CachingFilter输出的数据会根据浏览器发送的Accept-Encoding头信息进行Gzip压缩。经过笔者测试,Gzip压缩后的数据量是原来的1/4,速度是原来的4-5倍,所以缓存加上压缩,效果非常明显。在使用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) {final boolean ie6 = headerContains(request, "User-Agent", "MSIE 6.0");final boolean ie7 = headerContains(request, "User-Agent", "MSIE 7.0");return acceptsEncoding(request, "gzip") || ie6 || ie7;}? EHCache在Hibernate中的使用EHCache可以作为Hibernate的二级缓存使用。在hibernate.cfg.xml中需增加如下设置:&prop key="hibernate.cache.provider_class"&org.hibernate.cache.EhCacheProvider&/prop&然后在Hibernate映射文件的每个需要Cache的Domain中,加入类似如下格式信息:&cache usage="read-write|nonstrict-read-write|read-only" /&比如:&cache usage="read-write" /&最后在配置文件ehcache.xml中增加一段cache的配置,其中name为该domain的类名。&cache name="domain.class.name"maxElementsInMemory="10000"eternal="false"timeToIdleSeconds="300"timeToLiveSeconds="600"overflowToDisk="false"/&? EHCache的监控对于Cache的使用,除了功能,在实际的系统运营过程中,我们会比较关注每个Cache对象占用的内存大小和Cache的命中率。有了这些数据,我们就可以对Cache的配置参数和系统的配置参数进行优化,使系统的性能达到最优。EHCache提供了方便的API供我们调用以获取监控数据,其中主要的方法有://得到缓存中的对象数cache.getSize();//得到缓存对象占用内存的大小cache.getMemoryStoreSize();//得到缓存读取的命中次数cache.getStatistics().getCacheHits()//得到缓存读取的错失次数cache.getStatistics().getCacheMisses()? 分布式缓存EHCache从1.2版本开始支持分布式缓存。分布式缓存主要解决集群环境中不同的间的数据的同步问题。具体的配置如下:在配置文件ehcache.xml中加入&cacheManagerPeerProviderFactoryclass="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1, multicastGroupPort=4446"/&&cacheManagerPeerListenerFactoryclass="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"/&另外,需要在每个cache属性中加入&cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/&例如:&cache name="demoCache"maxElementsInMemory="10000"eternal="true"overflowToDisk="true"&&cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/&&/cache&总结EHCache是一个非常优秀的基于Java的Cache实现。它简单、易用,而且功能齐全,并且非常容易与Spring、Hibernate等流行的开源框架进行整合。通过使用EHCache可以减少网站项目中数据库服务器的访问压力,提高网站的访问速度,改善用户的体验。EhCacheCache (Spring Framework 4.3.8.RELEASE API)
JavaScript is disabled on your browser.
Spring Framework
Class EhCacheCache
org.springframework.cache.ehcache.EhCacheCache
All Implemented Interfaces:
public class EhCacheCache
implements
implementation on top of an
Costin Leau, Juergen Hoeller, Stephane Nicoll
Nested Class Summary
Nested classes/interfaces inherited from interface&org.springframework.cache.
Constructor Summary
Constructors&
Constructor and Description
(&ehcache)
Method Summary
All Methods&&&
Modifier and Type
Method and Description
Remove all mappings from the cache.
Evict the mapping for this key from this cache if it is present.
Return the value to which this cache maps the specified key.
&T&&valueLoader)
Return the value to which this cache maps the specified key, obtaining
that value from valueLoader if necessary.
Return the value to which this cache maps the specified key,
generically specifying a type that return value will be cast to.
Return the cache name.
Return the underlying native cache provider.
Associate the specified value with the specified key in this cache.
Atomically associate the specified value with the specified key in this cache
if it is not set already.
Methods inherited from class&java.lang.
, , , , , , , , , ,
Constructor Detail
EhCacheCache
public&EhCacheCache(&ehcache)
Parameters:
ehcache - backing Ehcache instance
Method Detail
public final&&getName()
Description copied from interface:&
Return the cache name.
Specified by:
&in interface&
getNativeCache
public final&&getNativeCache()
Description copied from interface:&
Return the underlying native cache provider.
Specified by:
&in interface&
public&&get(&key)
Description copied from interface:&
Return the value to which this cache maps the specified key.
Returns null if the cache contains no
otherwise, the cached value (which may be null itself) will
be returned in a .
Specified by:
&in interface&
Parameters:
key - the key whose associated value is to be returned
the value to which this cache maps the specified key,
contained within a
which may also hold
a cached null value. A straight null being
returned means that the cache contains no mapping for this key.
public&&T&&T&get(&key,
&T&&valueLoader)
Description copied from interface:&
Return the value to which this cache maps the specified key, obtaining
that value from valueLoader if necessary. This method provides
a simple substitute for the conventional "if cached, otherwise
create, cache and return" pattern.
If possible, implementations should ensure that the loading operation
is synchronized so that the specified valueLoader is only called
once in case of concurrent access on the same key.
If the valueLoader throws an exception, it is wrapped in
Specified by:
&in interface&
Parameters:
key - the key whose associated value is to be returned
the value to which this cache maps the specified key
public&&T&&T&get(&key,
Description copied from interface:&
Return the value to which this cache maps the specified key,
generically specifying a type that return value will be cast to.
Note: This variant of get does not allow for differentiating
between a cached null value and no cache entry found at all.
Use the standard
variant for that purpose instead.
Specified by:
&in interface&
Parameters:
key - the key whose associated value is to be returned
type - the required type of the returned value (may be
null to in case of a null
value found in the cache, the specified type is irrelevant)
the value to which this cache maps the specified key
(which may be null itself), or also null if
the cache contains no mapping for this key
public&void&put(&key,
Description copied from interface:&
Associate the specified value with the specified key in this cache.
If the cache previously contained a mapping for this key, the old
value is replaced by the specified value.
Specified by:
&in interface&
Parameters:
key - the key with which the specified value is to be associated
value - the value to be associated with the specified key
putIfAbsent
public&&putIfAbsent(&key,
Description copied from interface:&
Atomically associate the specified value with the specified key in this cache
if it is not set already.
This is equivalent to:
Object existingValue = cache.get(key);
if (existingValue == null) {
cache.put(key, value);
return existingV
except that the action is performed atomically. While all out-of-the-box
implementations are able to perform the put atomically,
the operation may also be implemented in two steps, e.g. with a check for
presence and a subsequent put, in a non-atomic way. Check the documentation
of the native cache implementation that you are using for more details.
Specified by:
&in interface&
Parameters:
key - the key with which the specified value is to be associated
value - the value to be associated with the specified key
the value to which this cache maps the specified key (which may be
null itself), or also null if the cache did not contain any
mapping for that key prior to this call. Returning null is therefore
an indicator that the given value has been associated with the key.
public&void&evict(&key)
Description copied from interface:&
Evict the mapping for this key from this cache if it is present.
Specified by:
&in interface&
Parameters:
key - the key whose mapping is to be removed from the cache
public&void&clear()
Description copied from interface:&
Remove all mappings from the cache.
Specified by:
&in interface&
Spring Framework关于Ehcache重启恢复缓存数据的问题。在线等_java吧_百度贴吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&签到排名:今日本吧第个签到,本吧因你更精彩,明天继续来努力!
本吧签到人数:0成为超级会员,使用一键签到本月漏签0次!成为超级会员,赠送8张补签卡连续签到:天&&累计签到:天超级会员单次开通12个月以上,赠送连续签到卡3张
关注:603,613贴子:
关于Ehcache重启恢复缓存数据的问题。在线等收藏
关于这个问题,我网上查阅了一部分资料。在web.xml中加了如下配置,&listener&
&listener-class&net.sf.ehcache.constructs.web.ShutdownListener&/listener-class&
&/listener&。而且在每次put的时候也都对cache进行flush()操作。操作完成以后本地会生成&.index&和&.data&的文件并且文件内都有内容。但是当服务器再次重启的时候,&.index&文件消失了,&.data&文件还在本地,服务器缓存内却没有数据。求助,哪位大神能帮帮忙
马尔代夫、泰国、中国、马来西亚多国酒店全部订一晚送一晚,3天限时优惠
来个大神帮帮忙啊。。。。。
还没有人回复。。。自己顶!d=====( ̄▽ ̄*)b,等到有人回复为止
大神们都在哪呢?出来帮帮忙,感激不尽!
我天,别沉啊。java吧是我最后的希望。。。
1.ehcache可以在程序突然中止(包括断电的情况下),将原来缓存中的数据在程序进行重启的时候重新加载到缓存中去。1)在web.xml中加入监听。
&listener&
&listener-class&net.sf.ehcache.constructs.web.ShutdownListener&/listener-class&
&/listener&2)在ehcache.xml中进行配置。
&!--overflowToDisk当内存中数据满时写到磁盘,diskPersistent硬盘持久化--&
&cache name=&authorCodecache& maxElementsInMemory=&1& overflowToDisk=&true&
eternal=&false& timeToIdleSeconds=&0& timeToLiveSeconds=&3600& diskPersistent=&true&&
&/cache&3)在对应缓存进行初始化的时候加上这句话。
System.setProperty(&net.sf.ehcache.enableShutdownHook&, &true&);
/**授权码缓存名*/ public static final String AUTHOR_CODE_CACHE = &authorCodecache&; public static Cache authorCodeC public static CacheM /*优先加载*/ static{
if (manager==null&&authorCodeCache == null) {
System.setProperty(&net.sf.ehcache.enableShutdownHook&, &true&);
manager = CacheManager.getInstance();
authorCodeCache = manager.getCache(AUTHOR_CODE_CACHE);
} }4)在get方法的时候使用flush().flush的作用是将缓存中的数据写入硬盘中。
解释一下:ehcache恢复数据是根据.index索引文件来进行数据恢复的。之前我是在put完以后,调用flush()方法,此时xxx.index文件会生成。但是当程序再次启动的时候,ehcache的一个方法会将.data文件和.index文件的修改时间进行比较,如果不符合直接将.index文件删除。所以程序运行以后,无法加载之前缓存中的数据。
在get方法处加上flush,这样ehcache会将索引(xxx.index)回写到磁盘。这样就不会担心程序非正常退出导致缓存丢失了。
添加了监听器后还要配置系统变量 System.setProperty(&net.sf.ehcache.enableShutdownHook&,&true&);
楼主在么?我ehcach持久化配置一直不行,不知道在哪里出什么问题,能帮看下?
java就看它,我就是看它找到工作的,
登录百度帐号推荐应用
为兴趣而生,贴吧更懂你。或

我要回帖

更多关于 ehcache cacheable 的文章

 

随机推荐