- 因爲要導入數據到Hive中,故開啓了一個新的線程,導入完數據後,要調用另一個服務的接口version+1然後保存到數據庫中。
- 開啓新線程:
@Override
public Map<String, Object> loadExceToHive(MultipartFile file, Long nodeId, String importType, CurrUserInfo currUserInfo,String token) throws Exception {
Thread thread = new Thread(new TagUdfDataImportThread(realPath, importDataVo, txtPath2, importType, importLogDO.getId(), tagUdfDO, currUserInfo, mainKeyFields, modelDO, webDate, p_exchange_date,token));
thread.start();
Map<String, Object> map = new HashMap<>();
map.put("id", importLogDO.getId());
return map;
}
@Override
public void run() {
try {
MetaServiceClient metaServiceClient = SpringApplicationContextHolder.getBean(MetaServiceClient.class);
this.tagUdfDO.setVersion(this.tagUdfDO.getVersion()+1);
metaServiceClient.tagUdfUpdate(this.tagUdfDO);
} catch (Exception e) {
e.printStackTrace();
}
}
@Component
@FeignClient(value = "meta-service", configuration = FeignConfiguration.class)
public interface MetaServiceClient {
@PostMapping("/tagUdf/update")
ApiResult tagUdfUpdate(@RequestBody TagUdfDO tagUdfDO);
}
- 這樣調用會出現空指針異常,主線程可以調用成功,子線程調用失敗。
解決方案:子線程中,新開啓一個請求,代碼如下:
@Override
public void run() {
try {
TagUdfService tagUdfService = SpringApplicationContextHolder.getBean(TagUdfService.class);
this.tagUdfDO.setVersion(this.tagUdfDO.getVersion()+1);
tagUdfService.tagUdfUpdate(tagUdfDO,token);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void tagUdfUpdate(TagUdfDO tagUdfDO,String token) {
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("token", token);
requestHeaders.add("content-type", MediaType.APPLICATION_JSON_UTF8.toString());
MultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
String json = JSON.toJSONString(tagUdfDO);
log.info(json);
JSONObject jsonObject =JSONObject.parseObject(json);
for(String key:jsonObject.keySet()){
requestBody.add(key, jsonObject.getString(key));
}
HttpEntity<String> requestEntity = new HttpEntity<String>(json, requestHeaders);
ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://meta-service/tagUdf/update", requestEntity, String.class);
log.info(" responseEntity :"+responseEntity.getBody());
}