gpt4 book ai didi

multithreading - Spring Boot Web应用程序中多个REST调用超时

转载 作者:行者123 更新时间:2023-12-03 12:59:43 25 4
gpt4 key购买 nike

我创建了一个Spring Boot(1.4.2)REST应用程序。 @RestController方法之一需要调用第三方API REST操作(RestOp1),该操作将返回100-250条记录。对于由RestOp1返回的每个记录,在同一方法内,必须调用同一第三方API(RestOp2)的另一个REST操作。我的第一次尝试涉及使用基于大小为100的固定线程池的Controller类级别的ExecutorService,以及一个Callable返回与RestOp2的响应相对应的记录:

// Executor thread pool - declared and initialized at class level
ExecutorService executor = Executors.newFixedThreadPool(100);

// Get records from RestOp1
ResponseEntity<RestOp1ResObj[]> restOp1ResObjList
= this.restTemplate.exchange(url1, HttpMethod.GET, httpEntity, RestOp1ResObj[].class);
RestOp1ResObj[] records = restOp1ResObjList.getBody();

// Instantiate a list of futures (to call RestOp2 for each record)
List<Future<RestOp2ResObj>> futureList = new ArrayList<>();

// Iterate through the array of records and call RestOp2 in a concurrent manner, using Callables.
for (int count=0; count<records.length; count++) {

Future<RestOp2ResObj> future = this.executorService.submit(new Callable<RestOp2ResObj>() {

@Override
public RestOp2ResObj call() throws Exception {
return this.restTemplate.exchange(url2, HttpMethod.GET, httpEntity, RestOp2Obj.class);
}
};

futureList.add(future);
});

// Iterate list of futures and fetch response from RestOp2 for each
// record. Build a final response and send back to the client.
for (int count=0; count<futureList.size(); count++) {

RestOp2ResObj response = futureList.get(count).get();
// use above response to build a final response for all the records.
}

至少可以说,以上代码的性能令人讨厌。 RestOp1调用(仅调用一次)的响应时间约为2.5秒,而RestOp2调用(针对每个记录调用)的响应时间约为1.5秒。但是代码执行时间在20到30秒之间,而不是预期的5到6秒!我在这里缺少基本的东西吗?

最佳答案

您正在调用的服务是否足够快以每秒处理那么多请求?

有一个名为AsyncRestService的RestService异步版本。为什么不使用它?

我可能会这样:

    AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(new ConcurrentTaskExecutor(Executors.newFixedThreadPool(100)));

asyncRestTemplate.exchange("http://www.example.com/myurl", HttpMethod.GET, new HttpEntity<>("message"), String.class)
.addCallback(new ListenableFutureCallback<ResponseEntity<String>>() {
@Override
public void onSuccess(ResponseEntity<String> result) {
//TODO: Add real response handling

System.out.println(result);
}

@Override
public void onFailure(Throwable ex) {
//TODO: Add real logging solution

ex.printStackTrace();
}
});

关于multithreading - Spring Boot Web应用程序中多个REST调用超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com