首页 > 解决方案 > 如何提高内部其他 REST 调用的 REST 调用的性能

问题描述

我正在创建一个端点来检索我的一些数据,在这个调用中它调用了 3 个不同的 REST 调用,因此它妨碍了我的应用程序的性能。

My Endpoint Code:

 1. REST call to get the userApps()
 2. iterate over userAPPs
    2.1 make REST call to get the appDetails
    2.2 make use of above response to call the 3rd REST call which returns list.
    2.3 iterate over the above list and filter out the required fields and put it in main response object.
 3.return response

因此,如此多的复杂性阻碍了性能。

我尝试添加多线程概念,但普通代码和多线程所花费的时间几乎相同。

条件是,我们不能修改 3 个外部 REST 调用来支持分页。

我们无法添加分页,因为我们没有任何数据库。有什么解决办法吗?

标签: javamultithreadingrestcachingpagination

解决方案


你不应该添加线程,你应该完全删除线程。即你应该让你的所有代码都是非阻塞的。这只是意味着所有的工作基本上都会在http-client的线程池中完成,而所有的等待都可以在操作系统的选择器中完成(这是我们想要的)。

假设您的 http 调用 return ,这里有一些代码是如何工作的CompletableFuture

public CompletableFuture<List<Something>> retrieveSomethings() {
    return retrieveUserApps().thenCompose(this::retriveAllAppsSomethings);
}

public CompletableFuture<List<Something>> retrieveAllAppsSomethings(List<UserApp> apps) {
    return CompletableFuture.allOf(
        apps.stream().map(this::retriveAppSomethings).toArray(CompletableFuture[]::new))
    .apply(listOfLists -> listOfLists.stream().flatMap(List::stream).collect(Collectors.toList()))
    .apply(this::filterSomethings);
}

public CompletableFuture<List<Something>> retreiveAppSomethings(UserApp app) {
    return retrieveAppDetails(app).thenCompose(this::retreiveAppDetailSomethings);
}

所有这一切都是为了让一切都变得非阻塞,所以所有可以并行运行的东西都并行运行。没有必要限制任何东西,因为一切都将在 http-client 的线程池中运行,这很可能是有限的。反正没关系,因为等待不会占用线程。

对于上面的代码,你所要做的就是实现retrieveUserApps(),retrieveAppDetails(app)retrieveAppDetailSometings(appDetail). 所有这些都应该返回 aCompletableFuture<>并使用启用异步的 http 客户端版本来实现。

这将使 1 个应用程序或 100 个应用程序的检索数据相同,因为所有这些都将并行运行(假设它们都花费相同的时间并且下游系统可以处理这么多并行请求)。


推荐阅读