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<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;

你可能感兴趣的:(springBoot,springBoot,springBoot临时存数据)