缓存ecache使用

1、配置ecache.xml文件内容如下:

      注释:代表默认临时文件路径   user.home 代表用户主目录  user.dir 代表当前工作目录



    
    
    
    
    

2、springmvc配置文件中添加如下配置:

    
    
        
            classpath:ehcache/ehcache.xml
        
    

    
    
        
    

3、代码中通过注解的方式 将cacheManager注入进来使用。例如:

    @Resource
    EhCacheCacheManager cacheManager;
     /**
     * 初始化数据字典缓存
     */
    public void initDictCatch(){
        Cache cache = cacheManager.getCache("dictCache");
        cache.clear();
        //排序规则
        List orders = new ArrayList();
        orders.add(Order.asc("dicType"));
        orders.add(Order.asc("dicKey"));
//        List> result = jdbcTemplate.queryForList("select * from sys_dic");
        List result = (List) hibernateTemplate.find("from DicBean order by dicType,dicKey");

//        List result =  this.getDataList(DicBean.class,null,orders);
        //用于存放字典类型
        List types = new ArrayList();
        Map> map = new HashMap>();
        for(DicBean dic : result){
            String keyType = dic.getDicType();
            if(!types.contains(keyType)){
                types.add(keyType);
            }
        }

        //封装cache
        for(int i=0;i chilmap = new HashMap();
            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 result = (List) hibernateTemplate.find("from DicBean where dicType=? order by dicKey",new Object[]{dictype});
            Map chilmap = new HashMap();
            Map> prentmap = new HashMap>();
            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  getCacheNames(){
        Collection cacheNames =cacheManager.getCacheNames();
        return cacheNames;
    }

 

你可能感兴趣的:(技术专栏,java,ehcache,缓存)