【问题标题】:How to make Java Rest API to return response after first half of processing, then continue the second half after return response?如何使Java Rest API在前半部分处理后返回响应,然后在返回响应后继续下半部分?
【发布时间】:2021-12-12 14:33:14
【问题描述】:

我有一个使用 Spring Boot 的 API 端点。 这个端点的作用是调用另外两个 API 端点并处理它们的响应。

流程的前半部分调用一个 API 端点,获取响应并将此响应与 202 Accepted 一起返回到表面。

202返回后,后台正在进行后半程。它从第一个 API 调用中获取响应并进一步处理它。

我尝试使用ExecutorCompletableFuture,但它们都在返回 202 后停止并且不会运行下半场,或者他们等到下半场完成才返回 202。

这可能实现还是我正在寻找错误的设计?

这里是一些示例代码:

@PostMapping("/user")
public ResponseEntity<?> processUser(@Valid @RequestBody UserRequestDto request,
                                            @RequestHeader("Authorization") String token) throws Exception {
    CompletableFuture<UserResponseDto> response = CompletableFuture.supplyAsync(() ->
            userService.processUser(request, token));
        
    userService.processUserSecond(response, token);

    return new ResponseEntity<>(response, HttpStatus.ACCEPTED);
}

【问题讨论】:

    标签: java spring multithreading asynchronous


    【解决方案1】:

    明确一点:REST 端点由两个调用组成 - processUserprocessUserSecond。您想获取processUser 的结果,返回其结果并异步触发processUserSecond 而无需等待其结果。

    请记住,在这种情况下,第一次调用必须是同步的,因为您要等待其结果返回。后者可以是异步的。

    @PostMapping("/user")
    public ResponseEntity<?> processUser(@Valid @RequestBody UserRequestDto request,
                                                @RequestHeader("Authorization") String token) 
    {
       // synchronous, waiting for the response to be returned
       UserResponseDto response = userService.processUser(request, token);
    
       // asynchronous, fired without waiting for the response
       CompletableFuture.runAsync(() -> userService.processUserSecond(response, token));
           
       // return the result of the first (an only) synchronous call 
       return new ResponseEntity<>(response, HttpStatus.ACCEPTED);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-19
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 2021-07-12
      • 2012-03-08
      • 2013-11-17
      • 1970-01-01
      相关资源
      最近更新 更多