我有客户端和服务器端应用程序,其会话时间不超过 30 秒。
我正在编写一个 REST API 来下载报告,有时包含大量数据,但会遇到超时。有没有更好的方法可以做到这一点,使其不超过 30 秒的时间限制?
这是服务器端的控制器:
@GetMapping("/download")
public void downloadReport() {
List<Person> people = getPeople(); // data retrieval logic
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
response.addHeader(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_OCTET_STREAM_VALUE);
for (String person : people) {
StreamUtils.copy(new ByteArrayInputStream(person.concat("\n").getBytes(StandardCharsets.UTF_8)),
response.getOutputStream());
}
response.flushBuffer();
}
这是客户端代码:
@GetMapping("/download")
public void downloadReport(@RequestParam MultiValueMap<String, String> downloadRequest, HttpServletResponse response) throws Exception {
ResponseEntity<byte[]> result = restClient.downloadReport(URI, downloadRequest);
if (result.getStatusCode().equals(HttpStatus.OK)) {
String fileName = result.getHeaders().getContentDisposition().getFilename();
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
response.addHeader("Content-Type", "application/octet-stream");
StreamUtils.copy(result.getBody(), response.getOutputStream());
response.flushBuffer();
} else {
throw new Exception("Could not download report.");
}
}
非常感谢任何建议。
嗯,您可以轻松地进行一项优化。无需先写入
ByteArrayInputStream
,然后将其复制到 OutputStream
。
@GetMapping("/download")
public void downloadReport() {
List<Person> people = getPeople(); // data retrieval logic
response.addHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
response.addHeader(HttpHeaders.CONTENT_TYPE,
MediaType.APPLICATION_OCTET_STREAM_VALUE);
try (PrintWriter writer = new PrintWriter(response.getOutputStream(), false, StandardCharsets.UTF_8)) {
for (String person : people) {
writer.write(person);
writer.write("\n");
}
response.flushBuffer();
}
}