美文网首页
【小结】ehcache缓存

【小结】ehcache缓存

作者: 桌面很乱 | 来源:发表于2019-07-22 20:10 被阅读0次

    常见的缓存技术

    • ehcache:hibernate底层

    • memcache:

    • redis:常用

    • jar包:


      360截图20190722191024047.jpg
    • ehcache使用步骤:
      1.导入jar包
      2.编写配置文件
      3.使用api
      获取数据先从缓存中获取
      若获取的值为空
      再去查询数据库,
      将数据放入缓存中

      public List<Category> findAll() throws Exception {
      //1.创建缓存管理器

        CacheManager cm=CacheManager.create(CategoryServiceImpl.class.getClassLoader().getResourceAsStream("ehcache.xml"));
        
        //2.获取指定的缓存
        Cache cache = cm.getCache("categoryCache");
        
        //3.通过缓存获取数据  将cache看成一个map即可
        Element element = cache.get("clist");
        
        List<Category> list=null;
        
        //4.判断数据
        if(element==null){
            //从数据库中获取
            CategoryDao cd=(CategoryDao) BeanFactory.getBean("CategoryDao");
            list=cd.findAll();
            
            //将list放入缓存
            cache.put(new Element("clist", list));
            
            System.out.println("缓存中没有数据,已去数据库中获取");
        }else{
            //直接返回
            list=(List<Category>) element.getObjectValue();
            
            System.out.println("缓存中有数据");
        }
        
        return list;
      

      }

    xml配置文件内容以及注释如下:

    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
    
    <diskStore path="C:/ehcache"/>
    
    <cache
            name="categoryCache"
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"
            />
            
    <!--
        默认缓存配置,
        以下属性是必须的:
            name :cache的标识符,在一个CacheManager中必须唯一。
            maxElementsInMemory : 在内存中缓存的element的最大数目。
            maxElementsOnDisk : 在磁盘上缓存的element的最大数目。
            eternal : 设定缓存的elements是否有有效期。如果为true,timeouts属性被忽略。
            overflowToDisk : 设定当内存缓存溢出的时候是否将过期的element缓存到磁盘上。
    
        以下属性是可选的:
             timeToIdleSeconds : 缓存element在过期前的空闲时间。
             timeToLiveSeconds : 缓存element的有效生命期。
             diskPersistent : 在VM重启的时候是否持久化磁盘缓存,默认是false。
             diskExpiryThreadIntervalSeconds : 磁盘缓存的清理线程运行间隔,默认是120秒.
             memoryStoreEvictionPolicy : 当内存缓存达到最大,有新的element加入的时候,
                移除缓存中element的策略。默认是LRU,可选的有LFU和FIFO
    
    -->
    </ehcache>
    

    相关文章

      网友评论

          本文标题:【小结】ehcache缓存

          本文链接:https://www.haomeiwen.com/subject/uohglctx.html