一个场景,需要使用一个提供大文件作为流输出的rest webservice,反之亦然,需要处理流并直接写入文件而不是内存。服务 :
@RequestMapping(value = "downloadFile", method = RequestMethod.GET)
public StreamingResponseBody getSteamingFile(HttpServletResponse response) throws IOException {
response.setContentType("application/octet-stream");
InputStream inputStream = new FileInputStream(new File("data\\test_big.txt"));
return outputStream -> {
int nRead;
byte[] data = new byte[1024];
System.out.println("Writing some bytes..");
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, nRead);
}
System.out.println("Completed #####");
outputStream.flush();
outputStream.close();
response.flushBuffer();
};
}
消费者路线:
.to("http4://localhost:8080/downloadFile")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
InputStream is = exchange.getIn().getBody(InputStream.class);
File ret = File.createTempFile("loadTest", "tmp");
FileOutputStream fos = new FileOutputStream(ret);
StreamUtils.copy(is, fos);
System.out.println("File Name "+ ret.getName());
is.close();
fos.flush();
fos.close();
}
});
256 JVM 在处理 300 MB 时内存不足,因为我的路由没有执行流式传输到文件。