2017-09-18 23 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()當一個任務需要依賴他人所使用。