使用RestTemplate大文件上传,总失败
环境:
jdk 1.8
springboot v2.2.1.RELEASE
配置:
nginx配置
#参数大小 client_max_body_size 2048M #超时时间 proxy_connect_timeout 600; proxy_read_timeout 600; proxy_send_timeout 600;
项目配置文件配置内容
#单个文件的最大上限 spring.servlet.multipart.max-file-size = 2048MB #单个请求的文件总大小上限 spring.servlet.multipart.max-request-size=2048MB
依然报错
添加配置类配置restTemplate
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate(ClientHttpRequestFactory factory) { RestTemplate restTemplate = new RestTemplate(factory); restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8)); restTemplate.getMessageConverters().add(new ByteArrayHttpMessageConverter()); restTemplate.getMessageConverters().add(new ResourceHttpMessageConverter()); return restTemplate; } @Bean public ClientHttpRequestFactory simpleClientHttpRequestFactory() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); //请求工厂类是否应用缓冲请求正文内部,默认值为true, // 当post或者put大文件的时候会造成内存溢出情况,设置为false将数据直接流入底层HttpURLConnection。 factory.setBufferRequestBody(false); factory.setConnectTimeout(150000); factory.setReadTimeout(150000); return factory; } }
代码中设置: factory.setBufferRequestBody(false);
该代码的意思是请求工厂类是否应用缓冲请求正文内部,默认值为true,当post或者put大文件的时候会造成内存溢出情况,设置为false将数据直接流入底层HttpURLConnection。
源码:
/** * Indicate whether this request factory should buffer the * {@linkplain ClientHttpRequest#getBody() request body} internally. * <p>Default is {@code true}. When sending large amounts of data via POST or PUT, * it is recommended to change this property to {@code false}, so as not to run * out of memory. This will result in a {@link ClientHttpRequest} that either * streams directly to the underlying {@link HttpURLConnection} (if the * {@link org.springframework.http.HttpHeaders#getContentLength() Content-Length} * is known in advance), or that will use "Chunked transfer encoding" * (if the {@code Content-Length} is not known in advance). * @see #setChunkSize(int) * @see HttpURLConnection#setFixedLengthStreamingMode(int) */ public void setBufferRequestBody(boolean bufferRequestBody) { this.bufferRequestBody = bufferRequestBody; }