gpt4 book ai didi

java - 如何在 Spring Boot 中使用 CompletableFuture 并行调用多个方法

转载 作者:行者123 更新时间:2023-11-29 06:50:02 27 4
gpt4 key购买 nike

我在 Spring Boot 中有一个 Web 服务,它需要向外部 Web 服务发出请求以检索多个货币对的实时汇率。

目前调用外部API的方法是这样的;

@Async
public CompletableFuture<Double> getBaseRateForCurrencyPair(String sourceCurrency, String targetCurrency) {
String key = sourceCurrency.toUpperCase() + targetCurrency.toUpperCase();

Double baseRate = 0.00;

String baseRateProviderUrl = "https://apilayer.net/api/live?access_key=" + currencyLayerAccessKey + "&source=" + sourceCurrency + "&currencies=" + targetCurrency;
HttpClientRequest clientRequest = new HttpClientRequest(baseRateProviderUrl);

try {
Response response = clientRequest.get();
String responseStr = response.body().string();

JSONObject jsonObject = new JSONObject(responseStr);
baseRate = AppHelper.round(jsonObject.getJSONObject("quotes").getDouble(key), 2);
} catch (Exception e) {
e.printStackTrace();
}

return CompletableFuture.completedFuture(baseRate);
}

我想做的是根据我们需要获取汇率的货币对数量,未知次数地调用此方法,等待所有货币对完成并存储结果,准备在 API 中返回响应。

我有一个方法可以接收源货币代码和目标货币汇率列表。

public RateResponse getLiveRates(String sourceCurrency, String[] targetCurrencies) {
RateResponse rateResponse = new RateResponse();

rateResponse.setSourceCurrency(sourceCurrency);

/* Loop through target currencies and start a thread for each */
Map<String, CompletableFuture<Double>> ratesMap = new HashMap<>();
for (String targetCurrency : targetCurrencies) {
ratesMap.put(targetCurrency, matrixHelper.getBaseRateForCurrencyPair(sourceCurrency, targetCurrency));
}

/* At this point, I would loop through the Map and grab the results, but only when all are finished */

return rateResponse;
}

我的问题是,我无法弄清楚如何等到所有异步调用完成后再开始遍历 Map 并检索结果。

最佳答案

你试过了吗CompletableFuture方法 allOf(CompletableFuture<?>... cfs) ?查找文档 here

关于java - 如何在 Spring Boot 中使用 CompletableFuture 并行调用多个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51477024/

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