首页 IT程序员内容详情

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

2021-07-25 10181 编程艺术家
import javax.annotation.PostConstruct;import javax.annotation.PreDestroy;import java.util.HashMap;import java.util.List;import java.util.Map;
 
@Componentpublic class CodeCache {    public static Map<String, TownNameDto> codeMap = new HashMap<String, TownNameDto>();    public static Map<String, CompanyModel> companyMap = new HashMap<String, CompanyModel>();
 
    @Autowired    private CityDao cityDao;
    @Autowired    private CompanyDao companyDao;
 
 
    @PostConstruct    public void init() {        //系统启动中。。。加载codeMap
        List<TownNameDto> codeList = cityDao.selectCityNameAndCodeALL();        for (TownNameDto code : codeList) {
            codeMap.put(code.getTownCode() + code.getValue(), code);
        }
        List<CompanyModel> 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<String, TownNameDto> cityModelMap = CodeCache.codeMap;
        Map<String, CompanyModel> companyModelMap = CodeCache.companyMap;


转载于:https://www.cnblogs.com/dcrenl/p/14005001.html

相关标签: # java

 暂无评论,快来抢沙发吧~

发布评论