使用多线程的 Java API 调用

问题描述 投票:0回答:1

第一次 API 调用返回 18000 条记录, 每个 18000 条记录都是另一个 API 调用,他们可以在每个 5-200 的范围内给出响应。必须调用这 200 个中的每一个,并且必须将响应保存在 DB

java multithreading rest completable-future
1个回答
-1
投票

您似乎有一些想要以非阻塞方式实现的场景,不确定是否有帮助,但我尝试使用这种方法 -

  1. 通过将它们分配为流来获取近18000的第一个API调用记录。
  2. 循环流并使用线程池提交获取下一组数据的任务,每条记录也在流中。
  3. 最后在同一个线程池中迭代 200 条记录流并根据您的喜好使用相同或另一个线程池保存在数据库中。 您可以使用 awaitTermination 方法来确保您的 main 方法在完成任务之前不会退出。这取决于您的项目设置。如果它是一个不会被终止的服务器,你可能不需要这个。
public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        System.out.println("Program start :: " + System.currentTimeMillis());
        Stream<String> first1800Stream = Stream.of("first api 1", "first api 2"); // user your http client to get API.

        first1800Stream.forEach(rec-> {
            cachedThreadPool.submit(() -> {
                Stream<String> next200Data = Stream.of(rec + "next200 1", rec + "next200 2"); //user your http client to get API.
                next200Data.forEach(nextrec -> {
                    cachedThreadPool.submit(() -> System.out.println("Persist in db" + nextrec)); // make your DB call
                });
            });
        });
        cachedThreadPool.awaitTermination(5000,TimeUnit.MILLISECONDS);
        cachedThreadPool.shutdown();
    }
© www.soinside.com 2019 - 2024. All rights reserved.