1. 编程方式
get-and-set, 可以针对到每条缓存的存放时间
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import java.util.concurrent.Callable;
public class CacheWrap {
private Cache ehcache;
public void set(String key, Object value, int expire) {
Element elem = new Element(key, value);
if (expire!=0)
{
elem.setTimeToLive(expire);
}
getEhcache().put(elem, true);
}
public Object get(String key) {
Element elem = getEhcache().get(key);
return (null != elem) ? elem.getObjectValue() : null;
}
public Object get(String key, Callable refreshSource, int expire) {
Element elem = getEhcache().get(key);
Object value = (null != elem) ? elem.getObjectValue() : null;
if (null == value && null != refreshSource) {
try {
value = refreshSource.call();
if (null != value) {
Element newElem = new Element(key, value);
newElem.setTimeToLive(expire);
getEhcache().put(newElem, true);
}
} catch (Exception ex) {
}
}
return value;
}
public Cache getEhcache() {
return ehcache;
}
public void setEhcache(Cache ehcache) {
this.ehcache = ehcache;
}
}
2. 注解方式
所有的缓存的时间都是根据配置决定
org.springframework.cache.annotation.Cacheable;
@Cacheable(value="tyacCache",key="'srvlist_'+#user_id+'_'+#appName")
public List<Tyacservice> getList(final Long user_id, String appName)....
3. 对应的spring和ehcache配置
ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="600"
timeToLiveSeconds="600" overflowToDisk="false" memoryStoreEvictionPolicy="LRU"/>
<cache name="tyacCache" maxElementsInMemory="10000" eternal="false"
overflowToDisk="false" timeToIdleSeconds="60" timeToLiveSeconds="60"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
applicationContext.xml
#1相关
<bean id="cacheWrap" class="cn.tianya.tyac.commom.CacheWrap">
<property name="ehcache" ref="ehCache"/>
</bean>
<bean id="ehCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
<property name="cacheManager">
<ref local="cacheManagerFactory"/>
</property>
<property name="cacheName">
<value>tyacCache</value>
</property>
</bean>
#2相关
<bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="/WEB-INF/ehcache.xml" />
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="cacheManagerFactory" />
<cache:annotation-driven cache-manager="cacheManager"/>