Streaming large file through several services with no storing in memory
I have service "A" with controller method:
@GetMapping("/file")
public ResponseEntity<StreamingResponseBody> getPdf() throws IOException {
File file = new File("My Movie.mp4");
if (!file.exists()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "My Movie.mp4");
StreamingResponseBody responseBody = outputStream -> {
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
//
}
};
return ResponseEntity.ok()
.headers(headers)
.body(responseBody);
}
It's working well and I can download large files (checked ~5Gb). Now I have service "B" that sends request to the service "A" at "/file" endpoint and I want to pass large files through 2 services without storing it in the memory of service "B". How to do that using springframework 3.2.0 restClient? Here is my not working implementation of the service "B", when i try use it just in browser, I get Exception: java.lang.OutOfMemoryError:
@GetMapping("/fetchAndStreamFile")
public ResponseEntity<StreamingResponseBody> fetchAndStreamFile() {
StreamingResponseBody responseBody = outputStream -> restClient
.get()
.uri("http://localhost:8081/file")
.retrieve()
.body(StreamingResponseBody.class);
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(responseBody);
}
Is there the best way passing large files through several services?
I've already googled 2 days and ChatGPT'ed!
- 本文标签: 家庭宠物
- 本文链接: https://www.coder6.net/article/2575
- 版权声明: 本文由蚂蚁原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权
热门推荐
-
浏览(195) 评论(0)