2015-09-14 22 views
1

配置彈簧如何與CompletionStage返回類型一起使用?考慮一個代碼:如何用spring處理CompletionStage?

@RequestMapping(path = "/", params = "p", produces = MediaType.APPLICATION_JSON_VALUE) 
@ResponseBody 
public CompletionStage<List<MyResult>> search(@RequestParam("p") String p) { 
    CompletionStage<List<MyResult>> results = ... 
    return results; 
} 

我得到了404,但我在日誌中看到該方法被觸發。 如果我改變這樣的簽名:

@RequestMapping(path = "/", params = "p", produces = MediaType.APPLICATION_JSON_VALUE) 
@ResponseBody 
public List<MyResult> search(@RequestParam("p") String p) { 
    CompletionStage<List<MyResult>> results = ... 
    return results.get(); 
} 

我看到的全成JSON數組。

如何製作CompletionStage適用於彈簧(4.2.RELEASE)?

修訂

爲了測試我寫了下面的方法:

@RequestMapping(path = "/async") 
@ResponseBody 
public CompletableFuture<List<MyResult>> async() { 
    return CompletableFuture.completedFuture(Arrays.asList(new MyResult("John"), new MyResult("Bob"))); 
} 

和它的作品。吳

我有測試此版本的未來:

@RequestMapping(path = "/async2") 
@ResponseBody 
public CompletableFuture<List<MyResult>> async2() { 
    AsyncRestTemplate template = new AsyncRestTemplate(); 
    //simulate delay future with execution delay, you can change url to another one 
    return toCompletable(template.getForEntity("https://www.google.ru/?gws_rd=ssl#q=1234567890-", String.class)) 
      .thenApply(
        resp -> template.getForEntity("https://www.google.ru/?gws_rd=ssl#q=1234567890-", String.class)) 
      .thenApply(
        resp -> template.getForEntity("https://www.google.ru/?gws_rd=ssl#q=1234567890-", String.class)) 
      .thenApply(
        resp -> template.getForEntity("https://www.google.ru/?gws_rd=ssl#q=1234567890-", String.class)) 
      .thenApply(
        resp -> template.getForEntity("https://www.google.ru/?gws_rd=ssl#q=1234567890-", String.class)) 
      .thenApply(
        resp -> template.getForEntity("https://www.google.ru/?gws_rd=ssl#q=1234567890-", String.class)) 
      .thenApply(resp -> Arrays.asList(new MyResult("John"), new MyResult("Bob"))); 
} 

有點AGLY,但是......作品!

所以我原來的方法有以下邏輯:

  1. 遍歷集合
  2. 通過AsyncRestTemplate
  3. 製作的異步調用的集合中的每集合元素
  4. 撥打電話給每個CompletableFuture
    • thenApply (變換結果)
    • thenCompose(使新的異步cal l with AsyncRestTemplate)
    • thenApply(轉換結果)
    • 最後,我將變換列表調用爲Completable,如here所述。

看來,未來的轉型是錯誤的。未來的連鎖可能會持續太久嗎?有任何想法嗎?

+0

這應該是默認情況下可用。發佈您在服務器上獲得的錯誤/日誌。 (作爲編輯而不是評論!)。 –

+0

已更新。日誌中沒有錯誤,但我已經做了一些實驗,可能會有所幫助。 – Cherry

回答

0

的問題是在該行:

@RequestMapping(path = "/" ... 

當改爲

@RequestMapping(path = "/1" ... 

完成未來突然變得工作。

P.S.我之前在映射中發現問題實際上已經打破了我的所有想法。可能有助於某人O :-)

相關問題