StreamingResponseBody-处理Servlet异步I/O请求
来源:互联网 发布:网络错误651怎么解决 编辑:程序博客网 时间:2024/06/10 02:47
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 responseOutputStream 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);
阅读全文
0 0
- StreamingResponseBody-处理Servlet异步I/O请求
- 关于异步I/O请求被同步处理的问题。。
- Servlet 3.0异步处理请求
- 设备I/O之“异步设备I/O请求”
- 异步处理Servlet接收到的请求
- 异步文件 I/O
- 异步I/O
- 异步I/O机制
- I/O 异步访问
- 异步I/O
- I/O异步demo
- 异步I/O
- 异步设备I/O
- 异步I/O
- python 异步I/O
- Linux异步I/O
- Nodejs 异步 I/O
- nodejs-异步I/O
- 动态连接库 (.so文件)
- Centos7-安装MySQL
- 数字IC工程师的技能树
- C编译: 使用gdb调试
- hdu2648
- StreamingResponseBody-处理Servlet异步I/O请求
- 什么是晶圆CMP的ILD?
- CH340芯片选型----包括串口并口芯片
- 电路板线路板PCB开发设计分享教程之(2)--系统规划
- 36、不一样的C++系列--单例类模板
- php----stream_socket_pair
- java的继承
- 鸟哥Linux学习之——关机与重启
- Golang简单的memcache实现