- 因为要导入数据到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());
}