ehcache緩存java
spring配置文件中關鍵(非關聯hibernate集成)spring
<!-- 設置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>
緩存
測試類app
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;this
import com.goldgov.officialdoc.common.BaseDao;
import com.goldgov.officialdoc.db.OdContract;spa
/**
* 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");
}.net
}
hibernate
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;
}
}
測試結果