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

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值