简体   繁体   English

如何执行异步计算并同时处理其他http请求?

[英]How to execute async calculation and handle other http requests at the same time?

I want to handle several http request simultaneously. 我想同时处理几个http请求。 What means that I want the thread that get the http request will move the handle of the request to another thread and will be available for getting new requests, until the handler will provide the result. 这意味着我希望获取http请求的线程将请求的句柄移动到另一个线程,并且可用于获取新的请求,直到处理程序提供结果为止。 I will appreciate if someone can show me how to it right. 如果有人可以告诉我如何正确操作,我将不胜感激。 Thanks! 谢谢!

I tried working with CompletableFuture, but apparently I am doing something wrong, since the thread that gets the request is blocked for getting new requests until the handler finished. 我尝试使用CompletableFuture,但是显然我做错了,因为获取请求的线程被阻止获取新请求,直到处理程序完成为止。

As you can see - only after the handler finished (10 seconds of sleep) - the request thread get the new request, so I have no advantage that the handler was executed in another thread. 如您所见-仅在处理程序完成后(睡眠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 DEBUG [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - get a request 2019-06-21 06:38:58,081 DEBUG [ForkJoinPool.commonPool-worker-1] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - finish waiting 2019-06-21 06:38:58,116 DEBUG [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - get a request 2019-06-21 06:39:08,113 DEBUG [ForkJoinPool.commonPool-worker-1] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - finish waiting 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 DEBUG [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]-完成等待

I found a way to do it not using completableFuture (that I am still don't understand how it is useful, if in the end you need to call the get() method and be blocked until it ends), but using the @Suspended AsyncResponse response , like agpt suggested. 我找到了一种不使用completableFuture的方法(我仍然不明白它的用处,如果最后您需要调用get()方法并在其结束之前被阻塞),而是使用@Suspended AsyncResponse response ,如建议的agpt。

Here is the code: 这是代码:

  @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 DEBUG [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - get a request 1 2019-06-23 09:54:20,158 DEBUG [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - the submit finish 1 2019-06-23 09:54:22,026 DEBUG [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - get a request 2 2019-06-23 09:54:22,026 DEBUG [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - the submit finish 2 2019-06-23 09:54:30,158 DEBUG [Thread-2] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - finish waiting 1 2019-06-23 09:54:32,027 DEBUG [Thread-3] [com.xconnect.np.test.superquery.suppliers.http.QueryResource] - finish waiting 2 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 DEBUG [grizzly-http-server-0] [com.xconnect.np.test.superquery.suppliers.http.QueryResource]-提交完成1 2019-06-23 09:54:22,026 DEBUG [grizzly-http-服务器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调试[Thread-2] [com.xconnect.np.test.superquery.suppliers.http.QueryResource ]-完成等待1 2019-06-23 09:54:32,027调试[Thread-3] [com.xconnect.np.test.superquery.suppliers.http.QueryResource]-完成等待2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM