【问题标题】:Keep calling a rest API until server completes the task继续调用rest API,直到服务器完成任务
【发布时间】:2020-05-10 05:28:26
【问题描述】:

我正在从 Spring Boot 应用程序(在 JAVA 11 中)同步调用 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 并检查文件是否准备好。

类似这样的:

  • 首先调用“/download” -> API 返回“正在生成文件”状态
  • 所以,5 秒后再次调用它 -> API 再次返回“正在生成文件”状态
  • 所以,5秒后再次调用-> API再次返回“正在生成文件”状态(但此时假设文件已生成)
  • 所以,5 秒后再次调用它 -> API 返回文件位置 URL
  • 停止调用 API 并执行后续操作

有什么方法可以实现吗?我尝试查看CompletableFuture@Scheduled,但我对这两个选项都很陌生,找不到任何方法在我的代码中实现它们。任何帮助,将不胜感激!

【问题讨论】:

标签: java spring-boot rest restful-url


【解决方案1】:

您可以使用 Java Failsafe Library。请参阅 [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";
}

【讨论】:

  • 谢谢,拉马钱德兰。我正在尝试您的解决方案,它确实会重复调用 API,但如果 API 引发异常,Failsafe 不会跳出循环。我正在尝试 Failsafe.abortIf() 和 Failsafe.abortWhen() 之类的方法,但它们对我不起作用。
  • @AMagic 使用.handleIf(it -&gt; false)等handleIf 方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-21
  • 1970-01-01
  • 1970-01-01
  • 2019-11-20
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多