简体   繁体   English

继续调用 rest API 直到服务器完成任务

[英]Keep calling a rest API until server completes the task

I am calling a REST API synchronously from a Spring boot app (in JAVA 11) to download a file.我正在从 Spring 启动应用程序(在 ZC71E8D17D18 下载 696 文件中)同步调用 REST API。

This is how the REST API looks like:这就是 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" 
        } 
    }

The API returns two things, either it returns the status of the file if it is generating the file (which takes anywhere from 5 seconds to 5 minutes or more), or the file location URL itself if the file is generated. API 返回两件事,如果正在生成文件,则返回文件的状态(这需要 5 秒到 5 分钟或更长时间),或者如果文件已生成,则返回文件位置 URL 本身。

The problem I am trying to solve is, I need to call this "/download" API every 5 seconds and check if the file is ready or not.我要解决的问题是,我需要每 5 秒调用一次“/download”API 并检查文件是否准备好。

Something like this:像这样的东西:

  • First call the "/download" -> API returns "file generation in progress" status首先调用“/download” -> API 返回“文件生成进行中”状态
  • so, call it again after 5 seconds -> API returns the "file generation in progress" status again所以,在 5 秒后再次调用它 -> API 再次返回“正在生成文件”状态
  • so, call it again after 5 seconds -> API returns the "file generation in progress" status again (But by this time assume that the file is generated)所以,5秒后再次调用-> API再次返回“正在生成文件”状态(但此时假设文件已生成)
  • so, call it another time after 5 seconds -> API returns the file location URL所以,在 5 秒后再次调用它 -> API 返回文件位置 URL
  • Stop calling the API and do the next things停止调用 API 并做接下来的事情

Is there a way I can achieve this?有没有办法可以做到这一点? I tried looking CompletableFuture & @Scheduled but I am so new to both of these options and couldn't find any way to implement them in my code.我试着寻找CompletableFuture & @Scheduled但我对这两个选项都很陌生,找不到任何方法在我的代码中实现它们。 Any help would be appreciated!任何帮助,将不胜感激!

You can make use of the Java Failsafe Library .您可以使用 Java故障安全库 Refer the answer from [ Retry a method based on result (instead of exception) .请参阅 [ Retry a method based on result (instead of exception)的答案。 I have modified the code from the answer to match your scenario.我已经修改了答案中的代码以匹配您的场景。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM