简体   繁体   English

建议:从我的服务并行调用另一个微服务

[英]Suggestion : Making parallel call from my service to another micro service

I have a requirement as follows我有一个要求如下

  • Make a DB call based on certain criteria and fetch list of result根据特定条件进行数据库调用并获取结果列表
  • For each record present in list, make a GET api call to a microservice对于列表中的每条记录,对微服务进行 GET api 调用
  • Consolidate all result from micro-service and give response整合所有来自微服务的结果并给出响应

I want to make the second step parallel.我想让第二步平行。 Now I know based on data that no more than 15 records will be present in list.现在我根据数据知道列表中不会出现超过 15 条记录。 So I thought of using executorservice for this.所以我想为此使用 executorservice 。

Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())

Now I am not very confident as to whether现在我不是很自信

  1. Is using ExecutorService the best approach for my scenario.使用ExecutorService是我的场景的最佳方法。 Or I should be using something else或者我应该用别的东西
  2. Should I create a new executor like Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()) or let container inject a managed Executor using @Autowired我应该创建一个像Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())这样的新执行Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())还是让容器使用@Autowired注入一个托管的 Executor

Since you have a List of records, you may iterate through it using parallelStream .由于您有一个记录List ,您可以使用parallelStream遍历它。

List<SomeObject> objectList = resultFromDB();
objectList.parallelStream()
          .map(obj -> makeApiCallInParallel(obj))
          .collect(Collectors.toList());

parallelStream will perform API calls in parallel. parallelStreamparallelStream执行 API 调用。 The number of parallel calls is limited by the number of threads of your CPU.并行调用的数量受 CPU 线程数量的限制。

You may increase it using JVM property:您可以使用 JVM 属性增加它:

-Djava.util.concurrent.ForkJoinPool.common.parallelism=20

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

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