用缓存优化查询

在商品分类的时候,每次页面跳转需要去连接数据库进行查询,这样的效率很低,所以就用缓存来优化程序.

把每次从数据库总获取的数据放到缓存中,每次获取的时候就从缓存开始获取

这里我们用ehcache技术

首先要导5个必须的包
ehcache
log4j
slf4j-api
slf4j-jdk
slf4j-log4j

    @Override
    public List<Category> findAll() throws SQLException {
        /*
         * 使用缓存优程序,先从缓存中获取数据
         *  获取到数据,直接返回
         *  没获取到数据,查询数据库,将记录存入缓存
         * */
        //读取配置文件
        CacheManager cacheManager = CacheManager.create(CategoryServiceImpl.class.getClassLoader().getResourceAsStream("ehcache.xml"));
        //从配置文件中获取缓存区
        Cache cache = cacheManager.getCache("categoryCache");
        //判断缓存中是否有list集合
        Element element = cache.get("list");
        //判断
        List<Category> list = null;
        if(element == null) {
            //没有缓存数据,从数据库中获取数据
            CategoryDao cd = new CategoryDaoImpl();
            list = cd.findAll();
            element = new Element("list", list);
            //放入缓存
            cache.put(element);
        }else {
            //缓存中有数据
            System.out.println("缓存中,有数据------------------");
            list = (List<Category>) element.getObjectValue();
        }
        return list;
    }
原文地址:https://www.cnblogs.com/learnjfm/p/7041670.html