在项目中利用Map实现数据缓存功能

在项目开发中,对于数据库中不经常更改,但需要经常查询的数据,可以使用Map将数据缓存,减少数据库IO次数,提升性能。一下代码是实现过去12个月,按月份查询每个月的进出厂数量,每个月的数量不会改变。

//首先定义一个全局私有变量map
private Map<String,List<Map<String, String>>> map = new HashMap<String,List<Map<String, String>>>();

//业务方法
public ItemEntity getMonthCardIssue() throws Exception {
//map对应key的value为空时,才走数据库查询,并将查询出的数据put进map里,下次查询时就不需要从数据库里查询
        List<Map<String, String>> list = map.get("getMonthCardIssue");
        if(list==null || list.isEmpty()) {
            list = this.findCardNum();
            map.put("getMonthCardIssue", list);
        }
        ItemEntity item = new ItemEntity();
        List<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
        List<String> listTitle = new ArrayList<String>();
        for (int i = list.size() - 1; i >= 0; i--) {
            HashMap<String, Object> vals = new HashMap<String, Object>();
            vals.put("value", list.get(i).get("EXITNUMB"));
            listItem.add(vals);
            int month = Integer.parseInt(list.get(i).get("MONTH").substring(4));
            listTitle.add(month + "月");
        }
        Collections.reverse(listTitle);
        item.setNumber(listItem);
        item.setTitle(listTitle);
        return item;
    }

这种方法在服务器重启时map会清空,可以实现一个接口map.clear()手动清空map

猜你喜欢

转载自www.cnblogs.com/zeevy/p/12745322.html
今日推荐