我正在生成 excel 文件并将其提供给 UI。 Excel 文件包含来自两个第三方 api 的数据。第一个第三方调用将返回数据列表,然后我比较了数据库表中的数据,比较后我需要调用第二个第三方 api 所以每次根据第一个第三方调用返回的数据调用第二个第三方api 就像第一个第三方调用返回 100 条记录,然后第二个第三方调用 100 次。 我怎么能在这里使用并发,因为任务是依赖的
我有 controller.java 文件调用服务方法并返回 excel 文件作为响应和 UI 正在下载
@GetMapping("/api/report")
public ResponseEntity < InputStreamResource > generateReport(
@ApiParam("fromDate") @RequestParam(value = "fromDate", required = false) String fromDate,
@ApiParam("toDate") @RequestParam(value = "toDate", required = false) String toDate) throws Exception {
InputStreamResource isr = null;
ByteArrayInputStream
export = null;
if (StringUtils.isBlank(fromDate) || StringUtils.isBlank(toDate)) {
throw new Exception(HttpStatus.BAD_REQUEST.value(), "from date and to date is required");
}
List < DateRange > dateRangeList = convertToListOfDateRangeObj(fromDate, toDate);
export = service.generateReport(dateRangeList);
isr = new InputStreamResource(
export);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.add("Content-Disposition", "attachment; filename=" + "Report.xls");
return ResponseEntity.ok().headers(headers).body(isr);
}
` public ByteArrayInputStream generateReport(List < DateRange > dateRangeList)
throws ParseException, IOException, HttpStatusCodeException, JSONException {
List <ExcelData> reportData = new ArrayList < > ();
List <ExcelData> finalReportData = new ArrayList < > ();
for (DateRange dateRange: dateRangeList) {
reportData = getData(dateRange.getFromDate(), dateRange.getToDate());
finalReportData.addAll(reportData);
}
//logic to generate excel (Apache POI) using data available in finalReportData list
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
workbook.write(outputStream);
return new ByteArrayInputStream(outputStream.toByteArray());
}`
private List <ExcelData> getData(String from, String to)
throws HttpStatusCodeException, UnsupportedEncodingException, JsonProcessingException, JSONException {
List <Excel> excelDataList = new ArrayList < > ();
List <ResponseData> dataDetails = new ArrayList < > ();
ResponseData list = firstThirdpartyCall(from, to, null);
for (ResponseData data: list.getData()) {
dataDetails.add(data);
}
dataDetails = dataDetails.stream()
.filter(s - > s.getName().indexOf("EA") == 0 || s.getName().indexOf("EE") == 0)
.collect(Collectors.toList());
List < String > matchingRecords = getMatchingRecordFromDB(
dataDetails.stream().map(s - > s.getName()).collect(Collectors.toList()));
dataDetails = dataDetails.stream().filter(s - > matchingRecords.contains(s.getName()))
.collect(Collectors.toList());
for (int i = 0; i < dataDetails.size(); i++) {
Info usersObj = secondThirdpartyCall(dataDetails.get(i).getId());
//further process like database calls business logic on usersObj
}
//After process, populating List<ExcelData> and returning
return excelDataList;
}
我也尝试过可完成的未来,但是像 restcall 这样的其他线程在后台工作,主线程将响应作为空 excel 文件给出,因为数据仍在其他线程中处理,所以我没有得到输出。我需要将我的 api 的响应时间缩短到几秒。
任何帮助将不胜感激 谢谢