使用 500k+ 元素列表的优化方法

问题描述

我正在寻求帮助,因为我不知道如何优化流程。

我必须调用一个服务,该服务返回一个包含超过 50 万个元素的列表(我不知道为什么,这些服务属于客户端),对于列表的每个元素,我必须再调用 2 个服务,然后在我们的数据库中保存一些属性,这最后一步不是问题,但是整个过程每个元素需要 1 到 2 秒,因此这段时间将需要 100 多个小时才能完成该过程。 我的方法如下,我有我的主要方法在这方法中我得到了大列表,然后我使用 parallelStream 来迭代列表的元素,然后我使用 CompletableFuture调用调用提到的 2 个服务的方法多于。我尝试将 parallelStream 更改为 stream 和 for-each ,尝试将主列表拆分为较小的列表和许多其他内容,但我没有看到更好的性能,我认为问题在于这两个服务的调用,但我想试试运气问这里。

我正在使用 java 11、spring,并且我使用 RestTemplate 来调用服务,这是我的代码

public void updatediscount() {
    //List with 500k elements        
    var relationshipList = relationshipService.getLargeList();
    //CompletableFuture to make the async calls to the method above
    relationshipList.parallelStream().forEach(level1 -> {
        CompletableFuture.runAsync(() -> relationshipService.asyncdiscountSave(level1));        
    });

}


//Second class
@Async("nameOfThePool")
 public void asyncdiscountSave(ElementOfList element) {
     //Logic to create request
     //.........
     var responseClients = anotherClass.getClients(element.getGroup1()) //get the first response with restTemplate
     var responseProducts = anotherClass.getProducts(element.getGroup2())//get the second response with restTemplate
     
     for (var client : responseClients) {
         for (var product : responseProducts) {
            //Here we just save some attributes of these objects on our DB
         }
     } 

 }

感谢您的帮助。

更新:

对于这种特殊情况,我唯一能做的改进是将线程池传递给可完成的未来,问题是我需要调用的服务的响应时间。

我决定采用第二种方法,大约需要 5 个小时才能完成,与第一种方法相比,这是可以接受的。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)