直接上代码:
@GetMapping("/report")
public String report() {
List<String> citys = Arrays.asList("宿城", "宿豫", "泗洪", "泗阳", "沭阳");
Stream<String> cityStream = citys.parallelStream();
List<HashMap<String, List<HashMap<String, String>>>> collect = cityStream.map(s -> {
try {
return getCalResult(s);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}).collect(Collectors.toList());
// System.out.println(collect);
Gson gson = new Gson();
String s = gson.toJson(collect);
return s;
}
private HashMap<String, List<HashMap<String, String>>> getCalResult(String city) throws ExecutionException, InterruptedException {
CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "msaj").thenApply(s -> mxajService.getMszj() + "");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "xsaj").thenApply(s -> mxajService.getXszj() + "");
CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> "xzaj").thenApply(s -> mxajService.getXzzj() + "");
CompletableFuture<List<HashMap<String, String>>> anyOf = CompletableFuture.allOf(future1, future2, future3).thenApply(new Function<Void, List<HashMap<String, String>>>() {
@Override
public List<HashMap<String, String>> apply(Void aVoid) {
try {
String r1 = future1.get();
String r2 = future2.get();
String r3 = future3.get();
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("msaj", r1);
HashMap<String, String> map2 = new HashMap<String, String>();
map2.put("xsaj", r2);
HashMap<String, String> map3 = new HashMap<String, String>();
map3.put("xzaj", r3);
List<HashMap<String, String>> result = Arrays.asList(map1, map2, map3);
return result;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
}).exceptionally(new Function<Throwable, List<HashMap<String, String>>>() {
@Override
public List<HashMap<String, String>> apply(Throwable throwable) {
return null;
}
});
HashMap<String, List<HashMap<String, String>>> map = new HashMap<>();
map.put(city, anyOf.get());
return map;
}