StreamingResponseBody-处理Servlet异步I/O请求

StreamingResponseBody-处理Servlet异步请求

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方法是一个回调函数,在使用这个接口时需要Override writeTo方法。

下面以下载Excel为例讲解一下如何使用:

//内部匿名类,Override writeTo 方法。

StreamingResponseBody 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);

猜你喜欢

转载自blog.csdn.net/zjhcxdj/article/details/73695292