首页 文章

如何用Spring处理CompletionStage?

提问于
浏览
1

如何配置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 适用于spring(4.2.RELEASE)?

UPDATED

为了测试,我写了以下方法:

@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")));
}

有点灵巧,但......工作!

所以我原来的方法有以下逻辑:

  • 迭代收集

  • 通过AsyncRestTemplate为每个集合元素进行异步调用

  • 调用集合中的每个CompletableFuture

  • thenApply (转换结果)

  • thenCompose (使用AsyncRestTemplate进行新的异步调用)

  • thenApply (转换结果)

  • 最后,我将变换List调用为Completable,如here所述 .

似乎未来的转型是错误的 . 难道未来的连锁店会e太久吗?有任何想法吗?

1 回答

  • 0

    问题出在那条线上:

    @RequestMapping(path = "/" ...
    

    当改成它时

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

    未来的完成突然变得有效 .

    P.S. 在发现映射中的问题之前,我已经全心全意 . 可以帮助某人O :-)

相关问题