使用CompletableFuture将代码放在线程池中执行并返回结果
可以使用Java的CompletableFuture来实现将代码放在线程池中执行,并将结果返回到api接口返回体。具体实现如下:
-
在方法返回类型前添加CompletableFuture,将方法返回值转换为CompletableFuture类型。
-
将整个方法体放在CompletableFuture.supplyAsync中,以异步方式执行。
-
在supplyAsync的操作中,将原来的返回值改为CompletableFuture.completedFuture,将结果包装为CompletableFuture类型。
-
在CompletableFuture的操作链中使用thenApplyAsync方法,将返回结果转换为需要的格式,并使用supplyAsync将操作放入线程池中执行。
-
最后使用CompletableFuture.join方法等待异步操作完成,并返回结果给api接口。
修改后的代码如下:
public CompletableFuture<JSONArray> getGeometryAsync(GisDto gisDto, String geometryUrl) {
return CompletableFuture.supplyAsync(() -> {
try (HttpResponse response = HttpUtil.createGet(geometryUrl).form(gisDto).execute()) {
if (response.getStatus() != 200) {
throw new BizException('gis异常');
}
String s = response.body().toString();
Dict dict = JSON.parseObject(s, Dict.class);
JSONArray jsonArray = (JSONArray) dict.get('data');
return CompletableFuture.completedFuture(jsonArray.stream()
.map(obj -> (JSONObject) obj)
.peek(jsonObject -> {
JSONObject geometry = jsonObject.getJSONObject('geometry');
JSONArray pointsArray = geometry.getJSONArray('points');
JSONArray innerArray = new JSONArray(pointsArray.size());
for (int i = 0; i < pointsArray.size(); i++) {
JSONArray innerPointsArray = pointsArray.getJSONArray(i);
JSONArray pointArray = new JSONArray(innerPointsArray.size());
for (int j = 0; j < innerPointsArray.size(); j++) {
JSONObject pointObj = innerPointsArray.getJSONObject(j);
double x = pointObj.getDouble('x');
double y = pointObj.getDouble('y');
JSONArray innerPointArray = new JSONArray(2);
innerPointArray.add(x);
innerPointArray.add(y);
pointArray.add(innerPointArray);
}
innerArray.add(pointArray);
}
geometry.put('points', innerArray);
})
.map(jsonObject -> CompletableFuture.supplyAsync(() -> {
// 使用线程池执行转换操作
// 这里可以添加更多的操作链
return jsonObject;
}))
.map(CompletableFuture::join)
.collect(Collectors.toCollection(JSONArray::new)));
} catch (Exception e) {
log.debug(e.getMessage());
throw e;
}
});
}
最后在api接口中调用getGeometryAsync方法,并使用CompletableFuture.join方法等待异步操作完成并返回结果,如下所示:
public JSONArray getGeometry(GisDto gisDto) {
CompletableFuture<JSONArray> future = getGeometryAsync(gisDto, geometryUrl);
return future.join();
}
原文地址: https://www.cveoy.top/t/topic/okz1 著作权归作者所有。请勿转载和采集!