简体   繁体   中英

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
  • 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. So I thought of using executorservice for this.

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

Now I am not very confident as to whether

  1. Is using ExecutorService the best approach for my scenario. 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

Since you have a List of records, you may iterate through it using parallelStream .

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

parallelStream will perform API calls in parallel. The number of parallel calls is limited by the number of threads of your CPU.

You may increase it using JVM property:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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