: Stream closed
场景:在使用输入流获取请求体中的数据时抛出IOException
原因:
@Async(AppConstant.ASYNC_POOL)
public void recognize(HttpServletRequest request) {
try (InputStream is = ()) {
byte[] buffer = new byte[1024];
int length;
StringBuilder stringBuilder = new StringBuilder();
while ((length = (buffer)) != -1) {
(new String(buffer, 0, length));
}
// 处理数据...
}
}
问题就出在@Async(AppConstant.ASYNC_POOL)注解上,意思是使用异步执行该方法,如果在还未读取完输入流中的数据时,请求已经结束,那么就会导致输入流关闭,最后抛出: Stream closed异常。
解决方法:读取请求体中的数据操作使用同步操作,后面的处理数据操作单独提成一个方法,做异步操作。
public void recognize(HttpServletRequest request) {
try (InputStream is = ()) {
byte[] buffer = new byte[1024];
int length;
StringBuilder data = new StringBuilder();
while ((length = (buffer)) != -1) {
(new String(buffer, 0, length));
}
handler(data);
}
}
@Async(AppConstant.ASYNC_POOL)
public void handler(String data) {
// 处理数据...
}