我有一個使用 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);
}
uj5u.com熱心網友回復:
明確地說: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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/341397.html
