J2EE 缓存使用

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"/>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值