2015-12-02 75 views
5

我有一个客户端需要将大量的大型json文件发布到服务器。我已经能够通过将每个文件读入内存并使用RestTemplate发布整个文件来实现它。但是,客户端很快就会耗尽处理大型json文件的内存。我想切换到流式方法,但无法弄清楚如何正确使用RestTemplate的FileInputStream。我找到了this question,并使用了接受答案中给出的代码,但我仍然看到内存使用情况和OutOfMemory异常,这些异常让我相信它不是在流式传输文件,而是仍然将它们完全读入内存。我究竟做错了什么?这是我目前所拥有的:使用RestTemplate POST InputStream

final InputStream fis = ApplicationStore.class.getResourceAsStream(path); 

final RequestCallback requestCallback = new RequestCallback() { 
    @Override 
    public void doWithRequest(final ClientHttpRequest request) throws IOException { 
     request.getHeaders().add("Content-type", "application/json"); 
     IOUtils.copy(fis, request.getBody()); 
    } 
}; 

final RestTemplate restTemplate = new RestTemplate(); 
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); 
requestFactory.setBufferRequestBody(false);  
restTemplate.setRequestFactory(requestFactory);  
final HttpMessageConverterExtractor<String> responseExtractor = 
     new HttpMessageConverterExtractor<String>(String.class, restTemplate.getMessageConverters()); 

restTemplate.execute("http://" + host + ":8080/upads-data-fabric" + "/ruleset", httpMethod, requestCallback, responseExtractor); 

回答

7

不要。使用Resource结合适当的RestTemplate#exchange方法。

使用Resource作为body创建HttpEntity。有ClassPathResource来表示类路径资源。默认情况下,RestTemplate注册一个ResourceHttpMessageConverter哪些流。

+1

嗯...它似乎仍然在将文件读入内存,并且我很快就会遇到OutOfMemory异常。我错过了什么吗?以下是我所做的http://pastebin.com/ytjHDjR1 – Tom

+1

而我的RestTemplate配置在这里http://pastebin.com/6Rf2x6i3 – Tom

+0

@Tom您是否在编写请求正文或读取响应正文时遇到问题?我正在回应请求。 ResourceHttpMessageConverter的源代码是[here](https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/main/java/org/springframework/http/converter/) ResourceHttpMessageConverter.java#L102)。你会注意到它使用'StreamUtils#copy',它使用了4096字节的缓冲区。 –