StreamingResponseBody-处理Servlet异步I/O请求
StreamingResponseBody
是
Spring 4.2
版本添加的一个新的接口,在
Controller
里处理输出流时非常有用。
我们在
java
中创建
I/O
输入输出流时,一般用完流后都要关闭流,但是在
Controller
里面,处理
Http request
是异步的,这个时候如果往
request
里写入流的时候,我们无法确定什么时候关闭流,例如在完成下载的功能的时候,需要下载比较大的
File Stream
,例如
Video File Stream
,Excel File Stream。这个时候如果不关闭流,会造成比较大开销,并且
File
的线程会一直开着。
StreamingResponseBody可以很有效的解决这个问题。
先看下这个接口的定义:A controller method return value type for asynchronous request processing where the application can write directly to the response
OutputStream without holding up the Servlet container thread.
大致意思是说一个Controller在处理异步请求的时候,StreamingResponseBody会直接把流写入到response的输出流中,并且不会占用Servlet容器线程。
再看下这个接口内容:
public interface StreamingResponseBody {
/**
* A callback for writing to the response body.
* @param outputStream the stream for the response body
* @throws IOException an exception while writing
*/
void writeTo(OutputStream outputStream) throws IOException;
}
这个接口里只有一个方法,writeTo方法是一个回调函数,在使用这个接口时需要O
verride writeTo
方法。
下面以下载Excel为例讲解一下如何使用:
//内部匿名类,Override writeTo 方法。
S
treamingResponseBody streamingResponseBody = new StreamingResponseBody() {
@Override
public void writeTo(OutputStream out) throws IOException {
//把创建的Excel文件流写入到out中。
createExcel(dataList, tiltle, headers, out);
}
};
return ResponseEntity.ok().contentType(MediaType.parseMediaType("application/vnd.ms-excel")).header("Content-Disposition", "attachment;filename = " + AppConstants.sdf.format(new Date())+ this.controllerPath + AppConstants.applicationName + ".xlsx").body(streamingResponseBody);