【问题标题】:Implementing thread per request in HTTP Streaming servlet在 HTTP Streaming servlet 中为每个请求实现线程
【发布时间】:2014-01-10 21:59:34
【问题描述】:

我正在实施 HTTP Streaming servlet 来向客户端发送推送通知。在那个容器中还有 Jersey JAX-RS REST 服务。

问题是当我在两个浏览器窗口中打开流时,我必须等到另一个请求完成。

我读过类似的话题 Servlet seems to handle multiple concurrent browser requests synchronously 并在两个不同的浏览器中打开流并使其工作。

我尝试使用 AsyncContext,但它不是流式传输,它允许同时打开浏览器选项卡,并在执行线程结束时将所有内容传递给浏览器。

我还尝试在两个浏览器选项卡中同时打开示例 JSP 页面并得到类似的结果。

    <HTML>
    <HEAD>
       <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
       <meta http-equiv="Pragma" content="no-cache">
    </HEAD>
    <BODY BGCOLOR="blue" TEXT="white">
    <% 
      try {
        for (int i=1; i < 100; i++) {
           out.print("<h1>"+i+"</h1>");
           out.flush();

           try {
                Thread.sleep(1000);
           } catch (InterruptedException e) {
                out.print("<h1>"+e+"</h1>");
           }
         }
       } catch (Exception e) {
           out.print("<h1>"+e+"</h1>");
       }
       out.print("<h1>DONE</h1>");
    %>
    </BODY>
    </HTML>

作为服务器,我使用的是 Apache Tomcat 7.0。但是使用另一个 servlet 容器不会有问题。

任何指针?

谢谢

【问题讨论】:

  • 是不是因为 Thread.sleep() 正在停止整个 Servlet 线程?

标签: java servlets push-notification http-streaming


【解决方案1】:

从 servlet 容器中进行自己的线程管理几乎从来都不是一个好主意。

关于 Tomcat 中的服务器推送,请参见此处:http://tomcat.apache.org/tomcat-7.0-doc/aio.html

您确定客户端轮询不会更容易吗?

【讨论】:

  • 我已经按照说明完成了,删除了 doGet 方法并实现了 CometProcessor 接口,删除了无限的 while 循环并设置了 NIO 连接器而不是默认的 HTTP。并实现了事件方法,如: public void event(CometEvent event) throws IOException, ServletException { if (event.getEventType() == CometEvent.EventType.BEGIN) { Here is my subscription logic... } } 它有效,但没有任何改变.
猜你喜欢
  • 1970-01-01
  • 2018-03-13
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 2012-01-04
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
相关资源
最近更新 更多