项目场景:
多线程请求数据
代码
private <T>List<T> executeTask(List<Callable> c){
ExecutorService executorService = Executors.newFixedThreadPool(8);
List<Future> priceFutureList = new ArrayList<>();
for (Callable callable : c) {
priceFutureList.add(executorService.submit(callable));
}
ArrayList<T> l = new ArrayList<>();
for (Future f : priceFutureList) {
try {
l.add((T) f.get());
} catch (InterruptedException | ExecutionException e) {
throw new RuntimeException(e);
}
}
executorService.shutdown();
return l;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Slf4j
public class PrometheusCallable implements Callable {
private PrometheusProxyService m;
private PromQLEnum promQLEnum;
private String instance;
private String prometheusID;
@Override
public Map<String,Integer> call() {
JsonObject ql = m.excutePromQL(promQLEnum, instance, prometheusID);
HashMap<String, Integer> map = new HashMap<>();
// TODO 有可能没有获取到label
try {
map.put(prometheusID,ql.get("data").getAsJsonObject().get("result").getAsJsonArray().get(0).getAsJsonObject().get("value").getAsJsonArray().get(1).getAsInt());
}catch (Exception e){
log.error("解析prometheus指标数据异常,异常参数,{}",ql);
}
return map;
}
}
获取数据
ArrayList<Callable> prometheusObjs = new ArrayList<>();
new ArrayList<>(this.GetPrometheusMap().values()).forEach(s -> {
prometheusObjs.add(new PrometheusCallable(prometheusProxyService,PromQLEnum.PROBE_SUCCESS,ipRegex,s));
});
List<Map<String,Integer>> l = this.executeTask(prometheusObjs);
//丑陋的写法
/*Map<String, Integer> map = l.stream().filter(Objects::nonNull).collect(Collectors.toList()).stream().filter(
stringIntegerMap -> !stringIntegerMap.isEmpty()
).collect(Collectors.toMap(
s -> (String)s.keySet().toArray()[0],
a -> (Integer)a.values().toArray()[0]
));*/
HashMap<String, Integer> map = new HashMap<>();
l.stream().filter(Objects::nonNull).collect(Collectors.toList()).forEach(map::putAll);
list.forEach( promModel -> promModel.setStatus(map.containsKey(this.GetPrometheusMap().get(promModel.getApplicationName()))?
map.get(this.GetPrometheusMap().get(promModel.getApplicationName())).toString():""));
this.GetPrometheusMap()//是一个映射,只是copy下来项目代码