[英]How to make Java Rest API to return response after first half of processing, then continue the second half after return response?
I have an API endpoint that's using Spring Boot.我有一个使用 Spring Boot 的 API 端点。 What this endpoint does is it calls two other API endpoints and processes their response.这个端点的作用是调用另外两个 API 端点并处理它们的响应。
The first half of the process calls one API endpoint, get the response and return this response with a 202 Accepted to the surface.该过程的前半部分调用一个 API 端点,获取响应并将此响应与 202 Accepted 返回到表面。
After the 202 has been returned, the background is undergoing the second half of the process. 202返回后,后台正在进行后半部分的处理。 Which is taking the response from the first API calls and further processing it.这是从第一个 API 调用中获取响应并进一步处理它。
I tried with Executor
or CompletableFuture
but both of them stopped after its return 202 and will not run the second half or they wait until the second half to complete only return the 202.我尝试使用Executor
或CompletableFuture
但它们都在返回 202 后停止并且不会运行下半部分,或者他们等到下半部分完成才返回 202。
Is this possible to achieve or am I looking into wrong design?这有可能实现还是我正在研究错误的设计?
Here is some sample code:下面是一些示例代码:
@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);
}
To make it clear: The REST endpoint consists of two calls - processUser
and processUserSecond
.明确地说:REST 端点由两个调用组成 - processUser
和processUserSecond
。 You want to get the result of the processUser
, return its result and fire the processUserSecond
asynchronously without waiting for its result.您想获取processUser
的结果,返回其结果并异步触发processUserSecond
而不等待其结果。
Remember, in that case, the first call must be synchronous since you wait for its result to be returned.请记住,在这种情况下,第一次调用必须是同步的,因为您要等待其结果返回。 The latter can be asynchronous.后者可以是异步的。
@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.