ehcache的简单运用

ehcache.xml配置文件内容如下 :

<?xml version="1.0" encoding="UTF-8"?>
<ehcache>


	<diskStore path="java.io.tmpdir" />


	<defaultCache maxElementsInMemory="10000" eternal="false"
		timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true" />
		
	<cache name="myCache" maxElementsInMemory="10000" eternal="false"
		timeToIdleSeconds="300" timeToLiveSeconds="600" overflowToDisk="true" />
		
</ehcache>

工具类内容如下 :

public enum  EHCache {
	
	CACHE_MY("myCache");
		
	private CacheManager cacheManager=new CacheManager();
	private Cache cache;
	private String cachename;
	
	private EHCache(String chchename){  
	 this.cache=(Cache) cacheManager.getCache(chchename);
	     }

	public Cache getCache() {
		return cache;
	}

	public void setCache(Cache cache) {
		this.cache = cache;
	}
	

	public String getCachename() {
		return cachename;
	}

	public void setCachename(String cachename) {
		this.cachename = cachename;
	}

	/*
	 * 通过名称从缓存中获取数据
	 */
	public Object getCacheElement(String cacheKey) throws Exception {  
	               net.sf.ehcache.Element e = (Element) cache.get(cacheKey);  
	   if (e == null) {  
	   return null;  
	         }  
	 return e.getValue();  
	       }

	/*
	 * 将对象添加到缓存中
	 */
	public void addToCache(String cacheKey, Object result) throws Exception {
		Element element = new Element(cacheKey, result);
		cache.put(element);
	}
	
	/**
	 * 清除缓存
	 * @param cachKey
	 * @return
	 */
	public boolean removeCacheElement(String cachKey){
		 net.sf.ehcache.Element e = (Element) cache.get(cachKey);
		 boolean sign=false;
		 if(e!=null){
			sign= cache.remove(cachKey);
		 }else{
			 sign=true;
		 }
		 return sign;
	}
}


测试类:

public class Test5 {  
              
    public static void main(String[] args){  
        EHCache ehCache = EHCache.CACHE_MY;   
         JSONObject obj = new JSONObject();    
         obj.put("name","lsz");    
         try {  
            ehCache.addToCache("cache_json",obj);  
            ehCache.addToCache("cache_str","q jkdsksllll");  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        String getobj = ehCache.getCacheElement("cache_json");  
     System.out.println("getobj")  
    }  
}  





                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值