我們會(huì)有在項(xiàng)目服務(wù)啟動(dòng)的時(shí)候就去加載一些數(shù)據(jù)或做一些事情這樣的需求,為了解決這樣的問(wèn)題,在Spring Boot 中,實(shí)現(xiàn)接口 CommandLineRunner 即可。
創(chuàng)建實(shí)現(xiàn)接口 CommandLineRunner 的類:
/**
* 監(jiān)聽(tīng)完成時(shí)觸發(fā)
*
* @author : Fredia
* @since : 2018年3月16日
* @version : v1.0.0
*/
@Configuration
public class AuthClientRunner implements CommandLineRunner {
@Autowired
private ServiceAuthConfig serviceAuthConfig;
@Autowired
private UserAuthConfig userAuthConfig;
@Autowired
private ServiceAuthFeign serviceAuthFeign;
@Override
public void run(String... args) throws Exception {
log.info("初始化加載用戶pubKey");
try {
refreshUserPubKey();
}catch(Exception e){
log.error("初始化加載用戶pubKey失敗,1分鐘后自動(dòng)重試!",e);
}
log.info("初始化加載客戶pubKey");
try {
refreshServicePubKey();
}catch(Exception e){
log.error("初始化加載客戶pubKey失敗,1分鐘后自動(dòng)重試!",e);
}
}
\ public void refreshUserPubKey(){
BaseResponse resp = serviceAuthFeign.getUserPublicKey(serviceAuthConfig.getClientId(), serviceAuthConfig.getClientSecret());
if (resp.getStatus() == HttpStatus.OK.value()) {
ObjectRestResponse<byte[]> userResponse = (ObjectRestResponse<byte[]>) resp;
this.userAuthConfig.setPubKeyByte(userResponse.getData());
}
}
public void refreshServicePubKey(){
BaseResponse resp = serviceAuthFeign.getServicePublicKey(serviceAuthConfig.getClientId(), serviceAuthConfig.getClientSecret());
if (resp.getStatus() == HttpStatus.OK.value()) {
ObjectRestResponse<byte[]> userResponse = (ObjectRestResponse<byte[]>) resp;
this.serviceAuthConfig.setPubKeyByte(userResponse.getData());
}
}
}