繁体   English   中英

通过 Java Spring 启动延迟呼叫外部 API 的最佳方法?

[英]Best way to delay a call an external API via Java Spring Boot?

所以我有一个调用 2 个 API 的 java 应用程序。

  1. 调用 API 以获取要生成的文件的请求
  2. 调用第二个API获取文件。

第一个 API 返回凭据以获取文件。 第二个返回文件,但可能需要几秒钟或几分钟才能生成。 解释要求生成文件和提取文件之间的时间延迟的最佳方法是什么? 一些重试逻辑应该是必要的,但在初始调用时它总是返回 4xx HTTP 响应。 进行此 api 调用的最佳方法是什么,也许有比使用 RestTemplate 顺序调用 2 个 api 更好的方法? 我想在第二次调用之前添加一个短时间延迟,但我想知道是否有更好的库或异步方法我可以使用它更有效。 我将不胜感激任何 2 美分谢谢!

如果这两个api的作者是你的伙伴,我觉得有更好的办法,比如文件生成器调用你的回调api,然后你调用第二个API来获取文件。 作为补充,考虑到上述过程中的意外异常,可能需要重试计划来获取丢失的文件。

但是如果你只是想更优雅地实现重试和异步代码,以下是我的想法

    //call the first API

    ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
    CompletableFuture<File> completionFuture = new CompletableFuture<>();
    completionFuture.whenComplete((file, thrown) -> {
      //do something when the retry schedule complete
    });

    final ScheduledFuture<?> checkFuture = executor.scheduleAtFixedRate(() -> {
    //Call the second API to get the file
    //if("have got the file successfully") {
    //    completionFuture.complete(the file);
    //} else {
    //    //do nothing
    //}
    }, 5, 1, TimeUnit.SECONDS);//set a reasonable schedule policy

    completionFuture.orTimeout(10, TimeUnit.SECONDS);//setting a timeout policy is probably necessary

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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