[英]Keep calling a rest API until server completes the task
我正在從 Spring 啟動應用程序(在 ZC71E8D17D18 下載 696 文件中)同步調用 REST API。
這就是 REST API 的樣子:
@GetMapping("/download/{userId}/{fileName}")
public String download(final int userId, final String fileName) {
if(requested file is available) {
return {file location URL}
} else {
Begin generating a new file (takes 5 seconds to more than 5 minutes)
return "file generation in progress"
}
}
API 返回兩件事,如果正在生成文件,則返回文件的狀態(這需要 5 秒到 5 分鍾或更長時間),或者如果文件已生成,則返回文件位置 URL 本身。
我要解決的問題是,我需要每 5 秒調用一次“/download”API 並檢查文件是否准備好。
像這樣的東西:
有沒有辦法可以做到這一點? 我試着尋找CompletableFuture
& @Scheduled
但我對這兩個選項都很陌生,找不到任何方法在我的代碼中實現它們。 任何幫助,將不勝感激!
您可以使用 Java故障安全庫。 請參閱 [ Retry a method based on result (instead of exception)的答案。 我已經修改了答案中的代碼以匹配您的場景。
private String downloadFileWithRetry() {
final RetryPolicy<String> retryPolicy = new RetryPolicy<String>()
.withMaxAttempts(-1)
.handleResultIf("file generation in progress"::equalsIgnoreCase);
return Failsafe
.with(retryPolicy)
.onSuccess(response -> System.out.println("Generated file Url is ".concat(response.getResult())))
.get(this::downloadFile);
}
private String downloadFile() {
return "file generation in progress";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.