如何使用Spring RestTemplate恢复下载?

时间:2019-02-08 18:41:47

标签: java spring spring-boot resttemplate

我正在使用RestTemplate从Nexus服务器下载文件(大约350 mb)。为此,this中提供的代码非常有效:

RestTemplate restTemplate // = ...;

// Optional Accept header
RequestCallback requestCallback = request -> request.getHeaders()
        .setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL));

// Streams the response instead of loading it all in memory
ResponseExtractor<Void> responseExtractor = response -> {
    // Here I write the response to a file but do what you like
    Path path = Paths.get("some/path");
    Files.copy(response.getBody(), path);
    return null;
};
restTemplate.execute(URI.create("www.something.com"), HttpMethod.GET, requestCallback, responseExtractor);

我想检查文件是否存在,然后尝试恢复下载:

...
if(Files.exists(path)) {
    log.info("{} exists. Attempting to resume download", path);
    Files.write(path, StreamUtils.copyToByteArray(response.getBody()), StandardOpenOption.APPEND);
} else {
    Files.copy(response.getBody(), path);
}

但这只会导致OOM错误:

java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Unknown Source) ~[na:1.8.0_191]
    at java.io.ByteArrayOutputStream.grow(Unknown Source) ~[na:1.8.0_191]
    at java.io.ByteArrayOutputStream.ensureCapacity(Unknown Source) ~[na:1.8.0_191]
    at java.io.ByteArrayOutputStream.write(Unknown Source) ~[na:1.8.0_191]
    ...

我已经使用带有curl的Range标头测试了该呼叫,并且确定是Nexus支持的。我是这样设置的:

long bytes = path.toFile().length();
...
request.getHeaders().setRange(Arrays.asList(HttpRange.createByteRange(bytes)));

我猜上面的内存错误是由于InputStream阻塞而发生的。所以我尝试改用Channel / Buffer:

...
try {
    if(Files.exists(path)) {
        log.info("{} exists. Attempting to resume download", path);
        ReadableByteChannel channel = Channels.newChannel(response.getBody());

        FileChannel fileChannel = FileChannel.open(path, StandardOpenOption.APPEND);
        fileChannel.tryLock();
        ByteBuffer buffer = ByteBuffer.allocate(4096);
        int bytesRead = 0;
        while((bytesRead = channel.read(buffer)) != -1) {
            fileChannel.write(buffer);
            buffer.clear();
        }

        fileChannel.close();    
    } else {
        Files.copy(response.getBody(), path);
    }
...

这至少将一些数据写入文件,但仍然失败。我对java.nio工具没有太多经验,所以可以提供任何帮助。

* edit:感谢您提供任何答案,但我被迫为此项目使用JDK 8。

1 个答案:

答案 0 :(得分:0)

如果要处理大文件,则需要以下代码行,以确保不会在内存中读取流:

SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setBufferRequestBody(false);     
restTemplate.setRequestFactory(requestFactory);