2017-09-18 22 views
0

我已经使用下拉向导创建了一个后端点。下拉列表中的异步技术

@POST 
@Timed 
public String runPageSpeed(@RequestParam String request) { 
    try { 
     JSONObject requestJSON=new JSONObject(request); 

     JSONArray urls=requestJSON.getJSONArray("urls"); 

     process(urls); // this takes around 10 minutes to complete 

     return "done"; 
    } catch (Exception e) { 
     throw new WebApplicationException("failed", Response.Status.INTERNAL_SERVER_ERROR); 

    } 
} 

process(urls);大约需要10分钟即可完成。所以如果我们称之为终点,则需要超过10分钟才能得到答复。 我想要process(urls);收到request收到urls后在后台运行。所以当用户点击这个URL时,他会在几秒钟内得到响应。

我尝试了下面的代码和线程。

@POST 
@Timed 
public String runPageSpeed(@RequestParam String request) { 
    try { 
     JSONObject requestJSON=new JSONObject(request); 

     JSONArray urls=requestJSON.getJSONArray("urls"); 

     Thread thread = new Thread() { 
      public void run() { 
       process(urls); // this takes around 10 minutes to complete 
      } 
     }; 
     thread.start(); 

     return "done"; 
    } catch (Exception e) { 
     throw new WebApplicationException("failed", Response.Status.INTERNAL_SERVER_ERROR); 

    } 
} 

这里我用了一个线程。所以它异步运行,用户在几秒钟内得到响应,并且process(urls);在后台运行。 这解决了我的问题。但这是否正确?如果我使用这种方法,是否有任何问题,因为每分钟可以有很多请求。 dropwizard有什么技巧可以处理这种异步性质?

+0

请查看https://jersey.github.io/documentation/latest/async.html –

回答

0

弟兄欢迎Java8,Dropwizard用户应促进使用CompletableFuture用于异步处理,因为它是用于处理异步处理最安全,最酷的方式。通过CompletableFuture您可以将重量级任务移至后台线程,同时继续执行轻量级任务,因此也可以向客户端发回响应。其是否使用第一个复杂的任务的返回值到第二功能或与广大各种方法提供
runAsync()
supplyAsync(通知失败

@POST 
@Timed 
public String runPageSpeed(@RequestParam String request) { 
    try { 
     JSONObject requestJSON=new JSONObject(request); 
     JSONArray urls=requestJSON.getJSONArray("urls"); 

     CompletableFuture<Void> future = CompletableFuture.runAsync(() -> { 
      try { 
       // perform heavyweight task 
       process(urls); // this takes around 10 minutes to complete 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     }); 
     // perform lightweight task 
     return "done"; 
    } catch (Exception e) { 
     throw new WebApplicationException("failed", 
    Response.Status.INTERNAL_SERVER_ERROR); 
    } 
} 

CompletableFuture在各个方面帮助)
thenApply()
thenAccept()thenRun()
异常()
手柄()
你也可以连接使用thenCompose(在CompletableFuturethenCombine()当一个任务需要依赖他人所使用。