【问题标题】:How to improve the performance of a REST call which internally other REST calls如何提高内部其他 REST 调用的 REST 调用的性能
【发布时间】:2018-10-23 16:04:09
【问题描述】:

我正在创建一个端点来检索我的一些数据,并在此调用中调用 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 调用来支持分页。

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

【问题讨论】:

  • 你用的是spring boot吗?
  • 由于调用依赖于 prev 的结果。调用,我们不能使调用异步。您可以通过使用 RPC 调用来减少休息时间。微服务架构也支持它们。
  • @Naveen 是的,我正在使用 Spring boot
  • @AdityaGupta 我以前没有使用过 RPC,但它会支持还是会减少 100 次迭代的时间?
  • RPC 减少了网络周转时间(或任何术语,用于将回复返回给调用者),因此单个调用会更快。就是这样,我们可以在这里做什么。

标签: java multithreading rest caching pagination


【解决方案1】:

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

下面是这个核心逻辑如何工作的一些代码,假设您的 http 调用返回 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)。所有这些都应该返回一个 CompletableFuture&lt;&gt; 并使用您的 http 客户端的异步版本实现。

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

【讨论】:

    猜你喜欢
    • 2018-01-06
    • 2015-11-30
    • 1970-01-01
    • 2018-05-06
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 1970-01-01
    相关资源
    最近更新 更多