[英]How to make Java Rest API to return response after first half of processing, then continue the second half after return response?
我有一个使用 Spring Boot 的 API 端点。 这个端点的作用是调用另外两个 API 端点并处理它们的响应。
该过程的前半部分调用一个 API 端点,获取响应并将此响应与 202 Accepted 返回到表面。
202返回后,后台正在进行后半部分的处理。 这是从第一个 API 调用中获取响应并进一步处理它。
我尝试使用Executor
或CompletableFuture
但它们都在返回 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);
}
明确地说:REST 端点由两个调用组成 - processUser
和processUserSecond
。 您想获取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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.