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 中:

Java 7

// The Enqueue servlet should be mapped to the "/enqueue" URL.
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("/");
  }
}

Java 8

// 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 中:

Java 7

// The Worker servlet should be mapped to the "/worker" URL.
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.
    // ...
  }
}

Java 8

// 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 項工作)。

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Java 適用的 App Engine 標準環境