非阻塞servlet执行中的内部500错误

时间:2018-12-14 08:09:11

标签: tomcat servlets

我正在尝试servlet不阻塞I / O。我正在使用Tomcat 8.5在Cloud Foundry容器中运行代码。

上传等于200 MB的文件时出现500个内部错误。

如果我上载20 MB左右的文件,同样可以正常工作。

我怀疑tomcat容器中的某些问题,即它无法处理io的非阻塞处理。

下面是我的代码

@WebServlet(urlPatterns = { "/asyncUpload" }, asyncSupported = true)
public class AsyncUploadTester extends HttpServlet {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        final AsyncContext acontext = request.startAsync();
        HttpServletResponse asyncresponse = (HttpServletResponse) acontext.getResponse();
        final ServletInputStream input = request.getInputStream();
        Instant start = Instant.now();
        logger.info("Inside doPost of asyncupload");

        input.setReadListener(new ReadListener() {
            byte buffer[] = new byte[4 * 1024];
            StringBuilder sbuilder = new StringBuilder();

            @Override
            public void onDataAvailable() {
                try {
                    do {
                        logger.info("reading data");
                        int length = input.read(buffer);
                        sbuilder.append(new String(buffer, 0, length));
                    } while (input.isReady());
                } catch (IOException ex) {
                    logger.error(" IO error from onDataAvailable" + ex);
                } catch (Exception e) {
                    logger.error(" error from onDataAvailable" + e);
                }
            }

            @Override
            public void onAllDataRead() {
                try {

                    asyncresponse.getWriter().println(" Async upload done");
                    Instant end = Instant.now();

                    Duration timeElapsed = Duration.between(start, end);
                    asyncresponse.getWriter().println(" Total time taken " + timeElapsed.toMillis() + " milliseconds");
                    asyncresponse.setStatus(HttpServletResponse.SC_CREATED);
                    logger.info("File upload done");

                } catch (IOException ex) {
                    logger.error("IO error from onAllDataRead" + ex);
                    asyncresponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                } catch (Exception e) {
                    logger.error(" error from onDataAvailable" + e);
                }
                acontext.complete();

            }

            @Override
            public void onError(Throwable t) {
                logger.error("error from onError" + t);
            }
        });
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        resp.getWriter().append(" Get called in Async upload");
    }
}

0 个答案:

没有答案