ehcache初使用

来源:互联网 发布:阿拉丁自有数据电解铝 编辑:程序博客网 时间:2024/06/16 16:34

ehcache简单使用步骤

ehcache:的作用

将常用的数据放到内存中,需要的时候直接从内存中获取,以减轻服务器的压力

使用步骤:

  • 1.jar包
  • 2.配置文件
  • 3.获取缓存管理者
  • 4.获取指定名称的缓存对象
  • 5.通过指定的key获取element
  • 6.判断element是否为空
    • 若为空,查询,将结果封装成Element,put进去
    • 若不为空,getObjectValue();

jar包

ehcache的lib包

配置文件

<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>

代码

public class CategoryServiceImpl implements CategoryService {    /**     *查询所有的分类【菜单功能】     */    @Override    public List<Category> findAll() throws Exception {        List<Category> clist = null;        //1.1 加载缓存配置文件        InputStream is = this.getClass().getClassLoader().getResourceAsStream("ehcache.xml");        //1.2 缓存管理器加载配置文件        CacheManager manager = CacheManager.create(is);        //1.3 创建缓存对象,缓存对象其实是一个map集合        Cache cache = manager.getCache("categoryCache");        //1.4 从缓存中取得数据【数据保存在element对象中,类似于map】        Element element = cache.get("clist");        //1.5 判断取得数据        if (element==null){            //查询出数据,存入缓存。element类似于map            //解耦合,使用工厂设计模式            CategoryDao dao = (CategoryDao) BeanFactory.getBean("CategoryDao");            element = new Element("clist",dao.findAll());            cache.put(element);            clist = (List<Category>) element.getObjectValue();            //System.out.println("缓存中没有数据,从数据库中查找,存入缓存中");        }else{            clist = (List<Category>) element.getObjectValue();            //System.out.println("从缓存中获得数据");        }        return clist;    }
原创粉丝点击