1、配置ecache.xml文件内容如下:
注释:<diskStore path="java.io.tmpdir"/>代表默认临时文件路径 user.home 代表用户主目录 user.dir 代表当前工作目录
<?xml version="1.0" encoding="UTF-8"?>
<ehcache name="es">
<diskStore path="java.io.tmpdir"/>
<!-- 字典项缓存-->
<cache name="dictCache"
maxEntriesLocalHeap="5000"
eternal="true"
overflowToDisk="false"
statistics="true">
</cache>
</ehcache>
2、springmvc配置文件中添加如下配置:
<!-- 字典项缓存管理-->
<bean id="cacheManagerFactory"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation">
<value>classpath:ehcache/ehcache.xml</value>
</property>
</bean>
<!-- 声明cacheManager -->
<bean class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="cacheManagerFactory"></property>
</bean>
3、代码中通过注解的方式 将cacheManager注入进来使用。例如:
@Resource
EhCacheCacheManager cacheManager;
/**
* 初始化数据字典缓存
*/
public void initDictCatch(){
Cache cache = cacheManager.getCache("dictCache");
cache.clear();
//排序规则
List<Order> orders = new ArrayList<Order>();
orders.add(Order.asc("dicType"));
orders.add(Order.asc("dicKey"));
// List<Map<String, Object>> result = jdbcTemplate.queryForList("select * from sys_dic");
List<DicBean> result = (List<DicBean>) hibernateTemplate.find("from DicBean order by dicType,dicKey");
// List<DicBean> result = this.getDataList(DicBean.class,null,orders);
//用于存放字典类型
List<String> types = new ArrayList<String>();
Map<String,Map<String,String>> map = new HashMap<String,Map<String,String>>();
for(DicBean dic : result){
String keyType = dic.getDicType();
if(!types.contains(keyType)){
types.add(keyType);
}
}
//封装cache
for(int i=0;i<types.size();i++){
Map<String,String> chilmap = new HashMap<String,String>();
for(DicBean dic : result){
if(types.get(i).equalsIgnoreCase(dic.getDicType())){
chilmap.put(dic.getDicKey(),dic.getDicValue());
}
}
map.put(types.get(i),chilmap);
cache.put(types.get(i),map);
}
}
/**
* 根据dictype获取字典项
*/
public Map getItemsByType(String dictype){
//获取字典项缓存
Cache cache = cacheManager.getCache("dictCache");
if(cache.get(dictype)==null){//说明缓存没有,则查询数据库 添加到缓存
List<DicBean> result = (List<DicBean>) hibernateTemplate.find("from DicBean where dicType=? order by dicKey",new Object[]{dictype});
Map<String,String> chilmap = new HashMap<String,String>();
Map<String,Map<String,String>> prentmap = new HashMap<String,Map<String,String>>();
for(DicBean dic : result){
chilmap.put(dic.getDicKey(),dic.getDicValue());
}
prentmap.put(dictype,chilmap);
cache.put(dictype,prentmap);
return chilmap;
}
Map map = (Map) cache.get(dictype).get();
return (Map) map.get(dictype);
}
/**
*清除缓存
*/
public SuccessMsg clearCache(String name){
//获取字典项缓存
Cache cache = cacheManager.getCache(name);
cache.clear();
return new SuccessMsg(true,"清除缓存成功!");
}
/**
*缓存列表
*/
public Collection<String> getCacheNames(){
Collection<String> cacheNames =cacheManager.getCacheNames();
return cacheNames;
}