<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<!-- maxElementsInMemory:设置基于内存的缓存可存放对象的最大数目。 -->
<!-- eternal:如果为true,表示对象永远不会过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false; -->
<!-- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了
timeToIdleSeconds属性值,这个对象就会过期。当对象过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。
如果该属性值为0,则表示对象可以无限期地处于空闲状态。 -->
<!-- timeToLiveSeconds:设定对象允许存在于缓存中的最长时间,以秒为单位。当对象自从被存放到缓存中后,如果处于缓存中的时间超过了
timeToLiveSeconds属性值,这个对象就会过期。当对象过期,EHCache将把它从缓存中清除。只有当eternal属性为false,该属性才有效。
如果该属性值为0,则表示对象可以无限期地存在于缓存中。timeToLiveSeconds必须大于timeToIdleSeconds属性,才有意义。 -->
<!-- overflowToDisk:如果为true,表示当基于内存的缓存中的对象数目达到了maxElementsInMemory界限后,会把益出的对象写到基于硬盘的缓存中。 -->
<!-- memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。
可以设置为FIFO(先进先出)或是LFU(较少使用)。 -->
<!-- 设定缓存的默认数据过期策略 -->
<defaultCache maxElementsInMemory="2000" eternal="false"
overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="150"
diskPersistent="false" memoryStoreEvictionPolicy="LRU" />
<!-- 自定义缓存策略-失效时间较短的缓存 -->
<cache name="test" maxElementsInMemory="20000" eternal="false"
overflowToDisk="false" timeToIdleSeconds="120" timeToLiveSeconds="150"
diskPersistent="false" memoryStoreEvictionPolicy="LRU" />
</ehcache>
@Cacheable(value="test", key="'test_'.concat(#id)")
public String queryById(String id) {
return id +"11"
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
<!--开启缓存的注解功能,否则注解无法生效-->
<cache:annotation-driven cache-manager="ehcacheCacheManager"/>
<!-- 声明缓存管理器 -->
<bean id="ehcacheCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehCacheFactory"></property>
</bean>
<!--指定工厂类及ehcache.xml文件位置-->
<bean id="ehCacheFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache/ehcache.xml"/>
</bean>
</beans>