欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入
Jetty 和 Comet
Jetty 服务器使用稍微不同的技术来支持 Comet 的可伸缩的实现。Jetty 支持被称作 continuations 的编程结构。其思想很简单。请求先被暂停,然后在将来的某个时间点再继续。规定时间到期,或者某种有意义的事件发生,都可能导致请求继续。当请求被暂停时,它的线程被释放。
可以使用 Jetty 的 org.mortbay.util.ajax.ContinuationSupport 类为任何 HttpServletRequest 创建 org.mortbay.util.ajax.Continuation 的一个实例。这种方法与 Comet 有很大的不同。但是,continuations 可用于实现逻辑上等效的 Comet.清单 6 显示清单 2 中的 weather servlet “移植” 到 Jetty 后的代码。
清单 6. Jetty Comet servlet
public class JettyWeatherServlet extends HttpServlet { private MessageSender messageSender = null; private static final Integer TIMEOUT = 5 * 1000; public void begin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { request.setAttribute(“org.apache.tomcat.comet”, Boolean.TRUE); request.setAttribute(“org.apache.tomcat.comet.timeout”, TIMEOUT); messageSender.setConnection(response); Weatherman weatherman = new Weatherman(95118, 32408); new Thread(weatherman).start(); } public void end(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { synchronized (request) { request.removeAttribute(“org.apache.tomcat.comet”); Continuation continuation = ContinuationSupport.getContinuation (request, request); if (continuation.isPending()) { continuation.resume(); } } } public void error(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { end(request, response); } public boolean read(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { throw new UnsupportedOperationException(); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { synchronized (request) { Continuation continuation = ContinuationSupport.getContinuation (request, request); if (!continuation.isPending()) { begin(request, response); } Integer timeout = (Integer) request.getAttribute (“org.apache.tomcat.comet.timeout”); boolean resumed = continuation.suspend(timeout == null ? 10000 : timeout.intValue()); if (!resumed) { error(request, response); } } } public void setTimeout(HttpServletRequest request, HttpServletResponse response, int timeout) throws IOException, ServletException, UnsupportedOperationException { request.setAttribute(“org.apache.tomcat.comet.timeout”, new Integer(timeout)); } }这里最需要注意的是,该结构与 Tomcat 版本的代码非常类似。begin、read、end 和 error 方法都与 Tomcat 中相同的事件匹配。该 Servlet 的 service 方法被覆盖为在请求第一次进入时创建一个 continuation 并暂停该请求,直到超时时间已到,或者发生导致它重新开始的事件。上面没有显示 init 和 destroy 方法,因为它们与 Tomcat 版本是一样的。该 servlet 使用与 Tomcat 相同的 MessageSender.因此不需要修改。注意 begin 方法如何创建 Weatherman 实例。对这个类的使用与 Tomcat 版本中也是完全相同的。甚至客户机代码也是一样的。只有 servlet 有更改。虽然 servlet 的变化比较大,但是与 Tomcat 中的事件模型仍是一一对应的。
希望这足以鼓舞人心。虽然完全相同的代码不能同时在 Tomcat 和 Jetty 中运行,但是它是非常相似的。当然,JavaEE 吸引人的一点是可移植性。大多数在 Tomcat 中运行的代码,无需修改就可以在 Jetty 中运行,反之亦然。因此,毫不奇怪,下一个版本的 Java Servlet 规范包括异步请求处理(即 Comet 背后的底层技术)的标准化。 我们来看看这个规范:Servlet 3.0 规范。
[1][2][3]
年轻是我们唯一拥有权利去编织梦想的时光