springmvc有时在通过request.getinputstream获取请求数据时占用太多时间

xesrikrc  于 2021-10-10  发布在  Java
关注(0)|答案(0)|浏览(291)

在springmvc中,当请求数据通过时,有时工作线程会被阻塞并占用太多时间(10秒到60秒) request.getInputStream .但通常情况下,它工作得很好。从调试日志中,我发现时间都在主机中 bufferedReader.read ,并且请求主体不太大。
环境:
网络服务器:下载1.3.23最终版本
SpringWeb:4.3.2.0版本
守则如下:

public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
        @Autowired
        private Logger logger = LoggerFactory.getLogger(this.getClass());

        private final String body;

        public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
            super(request);
            StringBuilder stringBuilder = new StringBuilder();
            BufferedReader bufferedReader = null;
            try {
                InputStream inputStream = request.getInputStream();
                if (inputStream != null) {
                    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                    char[] charBuffer = new char[128];
                    int bytesRead = -1;
                    while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                        stringBuilder.append(charBuffer, 0, bytesRead);
                    }
                } else {
                    stringBuilder.append("");
                }
            } catch (IOException ex) {
                throw ex;
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException ex) {
                        logger.error("close bufferedReader exception, detail:", ex);
                    }
                }
            }
            body = stringBuilder.toString();
        }

        @Override
        public ServletInputStream getInputStream() throws IOException {
            final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
            ServletInputStream servletInputStream = new ServletInputStream() {
                @Override
                public boolean isFinished() {
                    return false;
                }

                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setReadListener(ReadListener readListener) {

                }

                public int read() throws IOException {
                    return byteArrayInputStream.read();
                }
            };
            return servletInputStream;
        }

        @Override
        public BufferedReader getReader() throws IOException {
            return new BufferedReader(new InputStreamReader(this.getInputStream()));
        }

        public String getBody() {
            return this.body;
        }
    }

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题