1.使用前景 变量查询的时候,需要执行几十个sql语句查询,我们通过
CompletableFuture异步并发调用,极大的缩短了调用时间。
2.具体使用代码
public Map<String, Object> getRiskVar(List<String> sqlList) {
Map<String, Object> re = new HashMap<>();
List<CompletableFuture<String>> futures = new ArrayList<>();
for (String sql:sqlList) {
futures.add(CompletableFuture.supplyAsync(() -> getBigDataRiskVar(sql)));
}
//等待全部完成
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
//获取内容
for (CompletableFuture<String> future : futures) {
try {
String s = future.get();
if(StringUtil.isNotEmpty(s)) {
HashMap hashMap = JSON.parseObject(s, HashMap.class);
if (hashMap != null) {
re.putAll(hashMap);
}
}
} catch (InterruptedException | ExecutionException e) {
log.error("getRiskVar error:{}",e);
}
}
return re;
}
3.并发执行完所有的sql语句,获取返回结果,合并输出
runAsync方法不支持返回值。supplyAsync可以支持返回值
allOf:等待所有的执行完毕返回