【问题标题】:How to execute async calculation and handle other http requests at the same time?如何执行异步计算并同时处理其他http请求?
【发布时间】:2019-06-21 04:19:31
【问题描述】:

我想同时处理几个 http 请求。这意味着我希望获取 http 请求的线程将请求的句柄移动到另一个线程并且可用于获取新请求,直到处理程序提供结果。如果有人能告诉我如何正确,我将不胜感激。谢谢!

我尝试使用 CompletableFuture,但显然我做错了什么,因为在处理程序完成之前,获取请求的线程被阻止获取新请求。

如您所见 - 只有在处理程序完成后(10 秒的睡眠) - 请求线程才会收到新请求,所以我没有优势处理程序在另一个线程中执行。

@GET
@Path("/{phoneNumber}")
@Produces(MediaType.APPLICATION_JSON)
public Response query() throws InterruptedException, ExecutionException 
{   
    log.debug("get a request");                                         
    String message = calculateAsync().get();
    return Response.ok(message).build();
}

public Future<String> calculateAsync() throws InterruptedException 
{
    CompletableFuture<String> completableFuture = new CompletableFuture<String>();
    completableFuture = CompletableFuture.supplyAsync(() -> 
        {
            try {
                Thread.sleep(10000);
                log.debug("finish waiting");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return "hello";
        });
    return completableFuture;
}

2019-06-21 06:38:48,080 调试 [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - 得到一个 请求 2019-06-21 06:38:58,081 调试 [ForkJoinPool.commonPool-worker-1] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - 完成等待 2019-06-21 06:38:58,116 DEBUG [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - 得到一个 请求 2019-06-21 06:39:08,113 调试 [ForkJoinPool.commonPool-worker-1] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - 等待结束

【问题讨论】:

  • 我对 Java 8 不是很熟悉,但肯定有一个叫做 Callback 的东西,使用它你应该能够管理你的异步计算和返回响应。您可能还需要检查或更改您的 REST API 实现。 (虽然不确定)
  • 你能查一下callicoder.com/java-8-completablefuture-tutorial吗?看来您应该能够使用thenApply 方法处理它。而且我认为@Suspended AsyncResponse response 也很有用。
  • 也在本教程中:他的 get 方法仍然阻塞了主线程: CompletableFuture whatsYourNameFuture = CompletableFuture.supplyAsync(() -> { try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { throw new IllegalStateException(e); } return "Rajeev"; }); // 使用 thenApply() 将回调附加到 Future CompletableFuture greetingFuture = whatsYourNameFuture.thenApply(name -> { return "Hello " + name; }); // 阻塞并获取未来的结果。 System.out.println(greetingFuture.get());

标签: java http asynchronous completable-future grizzly


【解决方案1】:

我找到了一种不使用 completableFuture 的方法(我仍然不明白它有什么用,如果最后你需要调用 get() 方法并被阻止直到它结束),但是使用@Suspended AsyncResponse response,就像 agpt 建议的那样。

代码如下:

  @GET
  @Path("/{phoneNumber}")
  @Consumes("application/json")
   public void submit(@PathParam("phoneNumber") String phoneNumber, final @Suspended AsyncResponse response1) {
      log.debug("get a request " +phoneNumber);
      new Thread() {
         public void run() {
            String confirmation = process(phoneNumber);
            Response response = Response.ok(confirmation,
                                            MediaType.APPLICATION_XML_TYPE)
                                        .build();
            response1.resume(response);
         }
      }.start();
      log.debug("the submit finish " + phoneNumber);
   }


  public String process(String phoneNumber)
  {
        try {
            Thread.sleep(10000);
            log.debug("finish waiting "+phoneNumber);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String res = "hello" + phoneNumber;
        return res;
  }

2019-06-23 09:54:20,157 调试 [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - 得到一个 请求 1 2019-06-23 09:54:20,158 调试 [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - 的 提交完成 1 2019-06-23 09:54:22,026 DEBUG [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - 得到一个 请求 2 2019-06-23 09:54:22,026 调试 [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - 的 提交完成 2 2019-06-23 09:54:30,158 DEBUG [Thread-2] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - 完成等待 1 2019-06-23 09:54:32,027 DEBUG [Thread-3] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - 完成等待 2

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-23
    相关资源
    最近更新 更多