使用 Jetty AsyncProxyServlet 流式传输 HTTP 响应

Streaming HTTP responses with Jetty AsyncProxyServlet

我有一个服务器,可以流式传输各种内容,例如通过长期 HTTP 响应的日志输出。但是,当使用 Jetty 的代理 servlet 时,我无法让它流式传输响应(它在发送之前缓冲整个响应)。

使用覆盖普通 ProxyServlet class,以下似乎有效:

@Override
protected void onResponseContent(HttpServletRequest request, HttpServletResponse response, Response proxyResponse, byte[] buffer, int offset, int length, Callback callback) {
    super.onResponseContent(request, response, proxyResponse, buffer, offset, length, callback);
    try {
        response.getOutputStream().flush();
    } catch (IOException e) {
        log.warn("Error flushing", e);
    }
}

但是,在覆盖 AsyncProxyServlet 时这样做是行不通的。 (完整源代码 here。)

那么,两个问题:

  1. 当使用 ProxyServlet 时,是否在收到每一位内容后刷新?
  2. 有没有办法让它与 AsyncProxyServlet 一起使用?

成功了。无论是否使用异步,正确的方法都有效,即在创建 Jetty 服务器连接器时设置输出缓冲区大小。

HttpConfiguration httpConfig = new HttpConfiguration();
httpConfig.setOutputBufferSize(1024);
ServerConnector httpConnector = new ServerConnector(jettyServer,
        new HttpConnectionFactory(httpConfig));

默认为 32768。

(注意:不需要覆盖onResponseContent方法)