Java 任务队列示例

以下代码会将一个任务添加到队列中,并附上相关选项信息。

index.html 中:

<!-- A basic index.html file served from the "/" URL. -->
<html>
<body>
<p>Enqueue a value, to be processed by a worker.</p>
<form action="/enqueue" method="post">
    <input type="text" name="key">
    <input type="submit">
</form>
</body>
</html>

Enqueue.java 中:

// The Enqueue servlet should be mapped to the "/enqueue" URL.
// With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.
@WebServlet(
    name = "TaskEnque",
    description = "taskqueue: Enqueue a job with a key",
    urlPatterns = "/taskqueues/enqueue"
)
public class Enqueue extends HttpServlet {

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String key = request.getParameter("key");

    // Add the task to the default queue.
    Queue queue = QueueFactory.getDefaultQueue();
    queue.add(TaskOptions.Builder.withUrl("/worker").param("key", key));

    response.sendRedirect("/");
  }
}

Worker.java 中:

// The Worker servlet should be mapped to the "/worker" URL.
// With @WebServlet annotation the webapp/WEB-INF/web.xml is no longer required.
@WebServlet(
    name = "TaskWorker",
    description = "TaskQueues: worker",
    urlPatterns = "/taskqueues/worker"
)
public class Worker extends HttpServlet {

  private static final Logger log = Logger.getLogger(Worker.class.getName());

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String key = request.getParameter("key");

    // Do something with key.
    // ...
  }
}

在执行添加到此队列的任务时,系统会使用参数 key 在网址 /worker 处调用请求处理程序。任务将以 queue.xml 文件中设置的速率执行,或者以默认速率(即每秒 5 个任务)执行。