ehcache缓存

ehcache缓存

spring配置文件中关键(非关联hibernate集成)

<!-- 设置ehcache缓存开始 -->
 <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
  <property name="configLocation">
   <value>classpath:ehcache.xml</value>
  </property>
 </bean>
 <!-- 设置ehcacheFactory -->
 <bean id="levelOneCache" class="org.springframework.cache.ehcache.EhCacheFactoryBean">
         <property name="cacheManager">
             <ref local="cacheManager" />
         </property>
        <property name="cacheName">
            <value>configCache</value>
        </property>
 </bean>
 

测试类

package com.goldgov.officialdoc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import com.goldgov.officialdoc.common.BaseDao;
import com.goldgov.officialdoc.db.OdContract;

/**
 * ehcache缓存设置测试
 * @author  wangsl
 *
 */
public class EhcacheTest {
 private Cache cache;
 private static ThreadLocal<BaseDao> dao=new ThreadLocal<BaseDao>();
 private static ThreadLocal<HashMap> tmp=new ThreadLocal<HashMap>();
 static{

 
 /**
  * @param  args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
     Resource res = new ClassPathResource("applicationContext.xml");
           BeanFactory factory = new XmlBeanFactory(res);
           CacheManager cacheManager = (CacheManager) factory.getBean("cacheManager");
           Cache levelOneCache = cacheManager.getCache("levelOneCache");
          // BaseDao basic=(BaseDao) factory.getBean("basicDao");
           EhcacheTest cachet=new EhcacheTest();
           cachet.setCache(levelOneCache);
            for(int i=0;i<=5;i++){
                cachet.getCacheList("contrlist");
           }

 }
 

 
    public List getCacheList(String key){
     Element element=cache.get(key);
     Object cahceList=null;     List caresults=new ArrayList();
     if(element==null){ //判断数据是否存在 ,不存在,创建缓存工具
      List<OdContract> contrlist=new ArrayList<OdContract>();
      for(int i=0;i<=5;i++){
       OdContract od=new OdContract();
       od.setTitle("测试"+i);
       contrlist.add(od);
      }
      System.out.println("第一次调用cache缓存");
      cache.put(new Element("contrlist", contrlist));
      caresults=contrlist;
     }else{
      System.out.println("从缓存中取到");
      cahceList=element.getValue();
      List<OdContract> resutls=(List) cahceList;
      for(OdContract contr:resutls){
       System.out.println("name===="+contr.getTitle());
      }
      caresults=resutls;
     }
     return caresults;
    }
   
  
 public void setCache(Cache cache) {
  this.cache = cache;
 }

 }

测试结果

ehcache缓存

转载于:https://my.oschina.net/u/238082/blog/485746