原创

Streaming large file through several services with no storing in memory

温馨提示:
本文最后更新于 2024年04月12日,已超过 48 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

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!

正文到此结束
热门推荐
本文目录