2015-09-14 25 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 :-)

相关问题