码头7延续

时间:2011-05-22 03:30:38

标签: java jetty continuations

我正在使用jetty-7.4.1.v20110513和servlet-api-2.5

我尝试在以下servlet中使用continuation。

 import java.io.*;
 import java.util.*;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 import org.eclipse.jetty.continuation.*;



public class cs extends HttpServlet {

public void service(HttpServletRequest req, HttpServletResponse res)
throws java.io.IOException {

String reqId = req.getParameter("id");

Continuation cc = ContinuationSupport.getContinuation(req);

res.setContentType("text/plain");
res.getWriter().println("Request: "+reqId+"\tstart:\t"+new Date());
res.getWriter().flush();

cc.setTimeout(2000);
cc.suspend();

res.getWriter().println("Request: "+reqId+"\tend:\t"+new Date());
cc.complete();
}
}

我期待延迟2秒,但是当我从浏览器运行servlet时,我会得到如下输出:

Request: null   start:  Sat May 21 15:25:02 IST 2011
Request: null   end:    Sat May 21 15:25:02 IST 2011

2 个答案:

答案 0 :(得分:1)

我想你正在读这个tutorial。使用以下方法之一可以实现2秒的延迟:

  • 在第二个Thread.sleep(2000)之前添加res.getWriter().println()

  • 或删除Continuation.complete()调用,以使延续等待Continuation.setTimeout()中指定的最长时间。现在发生的是您立即通知 您的“计算”已完成(通过致电cc.complete()

答案 1 :(得分:1)

我终于找到了继续api。以下代码对我有用。感谢您的支持人员。

import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.continuation.*;

public class cs extends HttpServlet {

  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws java.io.IOException {

    String reqId = req.getParameter("id");

    Continuation cc = ContinuationSupport.getContinuation(req);

    res.setContentType("text/plain");
    res.getWriter().println("Request: " + reqId + "\tstart:\t" + new Date());
    res.getWriter().flush();

    cc.setTimeout(2000);
    cc.suspend();

    res.getWriter().println("Request: " + reqId + "\tend:\t" + new Date());
    if (cc.isInitial() != true) {
      cc.complete();
    }
  }
}

输出:

Request: null   start:  Sat May 21 15:25:02 IST 2011
Request: null   end:    Sat May 21 15:25:02 IST 2011
Request: null   start:  Sat May 21 15:25:04 IST 2011
Request: null   end:    Sat May 21 15:25:04 IST 2011