Springboot 在项目启动时将数据缓存到全局变量

声明:

有写字典数据不会频繁更新,但是会频繁查询,想要减少数据库链接次数,把内容缓存到项目的全局变量中,提高方法查询速度

 

代码:


import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class CodeCache {
    public static Map codeMap = new HashMap();
    public static Map companyMap = new HashMap();

    @Autowired
    private CityDao cityDao;
    @Autowired
    private CompanyDao companyDao;


    @PostConstruct
    public void init() {
        //系统启动中。。。加载codeMap
        List codeList = cityDao.selectCityNameAndCodeALL();
        for (TownNameDto code : codeList) {
            codeMap.put(code.getTownCode() + code.getValue(), code);
        }
        List companyModels = companyDao.selectCompanies();
        for (CompanyModel company : companyModels) {
            companyMap.put(company.getCode(), company);
        }


    }

    @PreDestroy
    public void destroy() {
        //系统运行结束
    }

    @Scheduled(cron = "0 0 0/2 * * ?")
    public void testOne() {
        //每2小时执行一次缓存
        init();
    }

}

使用:
 

//从缓存中获取城市;
        Map cityModelMap = CodeCache.codeMap;
        Map companyModelMap = CodeCache.companyMap;

 

你可能感兴趣的:(springboot)