方法加载时间长---1单例模式 2消息队列

背景:写了一个方法,遍历循环数据,耗时两三分钟,影响体验
一、想到了 static 静态变量或静态块,在项目启动时就加载变量,访问时可直接使用,避免了访问时加载时长的问题
二、由静态变量或静态块,想到了单例模式,在网上搜索有基于枚举的单例模式,参考:单例模式中为什么用枚举更好 、如何创建一个完美的单例模式、java单例之enum实现方式

自己写了一个单例,访问时长由两三分钟缩短为二三十秒,代码如下:

public class CitySingleton extends BaseController{
    private String json;

    private static volatile CitySingleton INSTANCE;

    private CitySingleton()throws Exception{
        json = packageCity();
    }

    public static CitySingleton getInstance() throws Exception{
        if(INSTANCE == null){
            synchronized(CitySingleton.class){
                //双重检查锁定
                if(INSTANCE == null){
                    INSTANCE = new CitySingleton();
                }
            }
        }
        return INSTANCE;
    }

    public String packageCity() throws Exception{
        List> provinces = new ArrayList>();
        List provinceList = cityService.getsByType(1);

        if(provinceList != null && !provinceList.isEmpty()){
            for (City province : provinceList) {
                List> cities = new ArrayList>();
                List cityList = cityService.getsByParent(province.getId());
                if(cityList != null && !cityList.isEmpty()) {
                    for (City city : cityList) {
                        List> areas = new ArrayList>();
                        List areaList = cityService.getsByParent(city.getId());
                        if(areaList != null && !areaList.isEmpty()) {
                            for (City area : areaList) {
                                Map areaMap = new HashMap();
                                areaMap.put("name",area.getCnname());
                                areaMap.put("code",area.getId());
                                areas.add(areaMap);
                            }
                        }
                        Map cityMap = new HashMap();
                        cityMap.put("name",city.getCnname());
                        cityMap.put("code",city.getId());
                        cityMap.put("sub",areas);
                        cities.add(cityMap);
                    }
                }
                Map provinceMap = new HashMap();
                provinceMap.put("name",province.getCnname());
                provinceMap.put("code",province.getId());
                provinceMap.put("sub",cities);
                provinces.add(provinceMap);
            }
        }
        return JSON.toJSONString(provinces);
    }

    public String getJson(){
        return json;
    }

    public void setJson(String json) {
        this.json = json;
    }
}

出于用户体验,二三十秒还是有些长,
三、现在考虑用消息队列异步执行的方式

你可能感兴趣的:(java)