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,但是......作品!
所以我原來的方法有以下邏輯:
- 遍歷集合 通過AsyncRestTemplate
- 製作的異步調用的集合中的每集合元素
- 撥打電話給每個CompletableFuture
thenApply
(變換結果)thenCompose
(使新的異步cal l with AsyncRestTemplate)thenApply
(轉換結果)- 最後,我將變換列表調用爲Completable,如here所述。
看來,未來的轉型是錯誤的。未來的連鎖可能會持續太久嗎?有任何想法嗎?
這應該是默認情況下可用。發佈您在服務器上獲得的錯誤/日誌。 (作爲編輯而不是評論!)。 –
已更新。日誌中沒有錯誤,但我已經做了一些實驗,可能會有所幫助。 – Cherry