
本文旨在解决java异步编程中,当`completablefuture`被不当嵌套时,调用`get()`或获取响应体时返回其状态而非实际结果的问题。通过分析错误根源,本文将展示如何正确地链式调用`completablefuture`,确保`thenapply`等方法能处理到期望的最终数据类型,从而避免获取到内部`completablefuture`对象本身。
理解CompletableFuture的嵌套问题
在Java的异步编程中,CompletableFuture是一个强大的工具,用于处理非阻塞操作。然而,不恰当的使用方式可能导致难以预料的结果。一个常见的陷阱是当一个CompletableFuture的内部值本身又是另一个CompletableFuture时,对其外部CompletableFuture执行操作可能会得到内部CompletableFuture对象本身的状态信息,而非其最终解析的数据。
考虑以下场景,一个Spring Boot应用提供了一个异步API:
不正确的RestController实现:
@RestControllerpublic class WorkerJController { @Autowired private WorkerJService service; @GetMapping(value = "/JobList", produces = MediaType.APPLICATION_JSON_VALUE) public CompletableFuture getJobListFunction() throws JsonProcessingException, InterruptedException { // 问题所在:service.getJobListFunction() 已经返回一个 CompletableFuture // CompletableFuture.completedFuture() 又将其包装了一层 return CompletableFuture.completedFuture(service.getJobListFunction()).thenApply(ResponseEntity::ok); }}
Service层实现:
立即学习“Java免费学习笔记(深入)”;
@Servicepublic class WorkerJService { public static ArrayList randomList = new ArrayList(); @Async public CompletableFuture getJobListFunction() throws JsonProcessingException, InterruptedException { randomList.add(new someThing("abc", "dfe")); ObjectMapper mapper = new ObjectMapper(); TimeUnit.SECONDS.sleep(5); // 模拟耗时操作 return CompletableFuture.completedFuture(mapper.writeValueAsString(randomList)); }}
当客户端通过HttpClient发送异步请求并尝试获取响应体时:
HttpClient client = HttpClient.newBuilder() .version(HttpClient.Version.HTTP_1_1) .followRedirects(HttpClient.Redirect.NORMAL) .connectTimeout(Duration.ofSeconds(20)) .build();HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:8080/JobList")) .timeout(Duration.ofMinutes(2)) .GET() .build();CompletableFuture<HttpResponse> cf = client .sendAsync(request, HttpResponse.BodyHandlers.ofString());// 假设这里在客户端获取了响应,并尝试访问其内容// cf.get().body() 可能会得到类似 {"cancelled":false,"done":true,"completedExceptionally":false,"numberOfDependents":0} 的状态信息
客户端接收到的响应体不是预期的JSON字符串,而是{“cancelled”:false,”done”:true,”completedExceptionally”:false,”numberOfDependents”:0}这样的CompletableFuture状态信息。
根源分析
问题的核心在于WorkerJController中的这行代码:
Seede AI
AI 驱动的设计工具
586 查看详情
return CompletableFuture.completedFuture(service.getJobListFunction()).thenApply(ResponseEntity::ok);
service.getJobListFunction() 方法已经返回了一个 CompletableFuture。CompletableFuture.completedFuture(service.getJobListFunction()) 的作用是将一个已经完成的值包装成一个 CompletableFuture。在这个场景中,这个“值”就是 service.getJobListFunction() 返回的那个 CompletableFuture 对象本身。因此,表达式 CompletableFuture.completedFuture(service.getJobListFunction()) 实际上创建了一个类型为 CompletableFuture<CompletableFuture> 的对象。当 thenApply(ResponseEntity::ok) 被调用时,thenApply 的函数参数 ResponseEntity::ok 会接收到 CompletableFuture 作为其输入(因为它是外部 CompletableFuture 解析后的值)。ResponseEntity.ok() 方法接受一个对象作为响应体。当它接收到一个 CompletableFuture 对象时,它会将其作为响应体直接封装到 ResponseEntity 中。最终,客户端获取到的 ResponseEntity 的主体就是那个尚未解析的 CompletableFuture 对象。当这个对象被序列化(例如,通过HTTP响应体传输)时,它的 toString() 或序列化器会输出其内部状态信息,而不是它最终将解析到的 String 值。
简而言之,我们创建了一个“双层”的CompletableFuture,而thenApply只处理了外层,将内层CompletableFuture本身作为数据传递了出去。
解决方案:正确链式调用CompletableFuture
解决这个问题的方法是避免不必要的嵌套,直接对 service.getJobListFunction() 返回的 CompletableFuture 进行链式操作。
修正后的RestController实现:
@RestControllerpublic class WorkerJController { @Autowired private WorkerJService service; @GetMapping(value = "/JobList", produces = MediaType.APPLICATION_JSON_VALUE) public CompletableFuture<ResponseEntity> getJobListFunction() throws JsonProcessingException, InterruptedException { // 直接对 service.getJobListFunction() 返回的 CompletableFuture 进行链式操作 return service.getJobListFunction().thenApply(ResponseEntity::ok); }}
解释:
service.getJobListFunction() 返回一个 CompletableFuture。thenApply(ResponseEntity::ok) 会等待这个 CompletableFuture 完成。一旦 CompletableFuture 完成,它的内部 String 值(即 mapper.writeValueAsString(randomList) 的结果)会被提取出来。这个 String 值随后作为参数传递给 ResponseEntity::ok。ResponseEntity.ok(String body) 会创建一个 ResponseEntity 对象。最终,getJobListFunction() 方法返回一个 CompletableFuture<ResponseEntity>,其中包含了我们期望的JSON字符串。
通过这种方式,thenApply 能够正确地处理到 CompletableFuture 最终解析的 String 值,并将其封装到 ResponseEntity 中,而不是封装 CompletableFuture 对象本身。
关键注意事项与最佳实践
避免不必要的嵌套: 当一个方法已经返回 CompletableFuture 时,不要再使用 CompletableFuture.completedFuture() 去包装它。理解 thenApply 与 thenCompose:thenApply(Function fn):用于对 CompletableFuture 的结果进行同步转换。fn 的返回值不是 CompletableFuture。例如,CompletableFuture.thenApply(t -> U) 结果是 CompletableFuture。thenCompose(Function fn):用于将一个 CompletableFuture 的结果扁平化为另一个 CompletableFuture。fn 的返回值是一个 CompletableFuture。例如,CompletableFuture.thenCompose(t -> CompletableFuture) 结果是 CompletableFuture。在我们的例子中,因为 ResponseEntity::ok 返回的是 ResponseEntity 而非 CompletableFuture,所以 thenApply 是正确的选择。如果 ResponseEntity::ok 自身也是一个异步操作返回 CompletableFuture,那么就应该使用 thenCompose。明确返回类型: 始终确保你的 CompletableFuture 返回的泛型类型是你最终期望的数据类型,而不是另一个 CompletableFuture。异常处理: 在实际应用中,不要忘记为 CompletableFuture 链添加异常处理机制,例如使用 exceptionally() 或 handle()。
总结
正确使用 CompletableFuture 的链式操作是编写高效、可维护的异步Java代码的关键。通过避免不必要的 CompletableFuture 嵌套,并根据转换操作的返回值类型(是否为 CompletableFuture)选择合适的链式方法(thenApply 或 thenCompose),可以确保我们始终能够获取到异步操作的最终实际结果,而不是中间状态或未解析的对象。理解这些细微之处将大大提升异步编程的质量和可靠性。
以上就是Java中正确处理嵌套CompletableFuture并获取实际结果的教程的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1074735.html
微信扫一扫
支付宝扫一扫