业务场景,在项目开发的过程中我们经常会遇到一些数据基本不变,但有可能需要频繁的从网络或者数据库的获取,这时我们就可在项目启动的时候初始化一次就好。
下面我们以发短信时需要加上国家编码为例:
首先我们需求是在项目启动的时候初始化这个数据的话,这个实现需求的话需要实现InitializingBean接口。这样只要项目启动时数据就会初始化。话不多说直接上代码
package com.hongyu.config;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSONArray;
import com.hongyu.domain.vo.CountryVo;
import com.hongyu.untils.USDT4HttpUtils;
import lombok.extern.slf4j.Slf4j;
/**
* 初始化国家编码数据
* @author Administrator
*
*/
@Slf4j
@Component
public class CountryInitService implements InitializingBean{
private static ConcurrentHashMap<String, CountryVo> countries = new ConcurrentHashMap<String, CountryVo>();
/**
* 根据国家编码获取数字代码
* @param countryCode
* @return
*/
public String getTelephoneCode(String countryCode) {
CountryVo countryDto = countries.get( countryCode );
if (countryDto == null) {
return null;
}
return countryDto.getTelephoneCode();
}
/**
* 判断国家编码是否存在
* @param countryCode
* @return
*/
public Boolean isEnable(String countryCode) {
CountryVo countryDto = countries.get( countryCode );
if (countryDto == null) {
return false;
}
return countryDto.getEnable();
}
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
initProvince();
System.out.println(getTelephoneCode("CN"));
}
/**
* 初始化
*/
private static void initProvince() {
String url = "https://citex-default.oss-cn-hongkong.aliyuncs.com/country.json";
try {
String res = USDT4HttpUtils.httpGet(url);
List<CountryVo> list = JSONArray.parseArray(res, CountryVo.class);
Map<String, CountryVo> map = list.stream().collect( Collectors.toMap( CountryVo::getId, Function.identity()) );
countries.putAll( map );
} catch (Exception e) {
log.error("执行初始化代码失败", e);
}
}
}