public JSONArray getPlayUrl(List<String> ids) throws Exception { long start = System.currentTimeMillis(); JSONObject user = getToken(); String token = user.getString("token_type") + " " + user.getString("access_token"); JSONArray jsonArray = new JSONArray(); ExecutorService executorService = Executors.newFixedThreadPool(10); CompletionService<JSONObject> completionService = new ExecutorCompletionService<>(executorService); for (String id : ids) { Callable<JSONObject> callable = () -> { JSONObject json; String param = "id=" + id + "&userId=" + user.get("user_id"); json = JSON.parseObject(HttpUtils.doGet(getPlayUrl, param, token)); log.info("中台返回设备流地址url:{}", json.getJSONObject("data")); return json.getJSONObject("data"); }; completionService.submit(callable); } for (int i = 0; i < ids.size(); i++) { Future<JSONObject> future = completionService.take(); jsonArray.add(future.get()); } executorService.shutdown(); long end = System.currentTimeMillis(); log.info("同步中台2.0耗时:{}", (start - end)); return jsonArray; }这段代码返回慢,能优化一下嘛
时间: 2024-03-28 12:42:35 浏览: 154
可以考虑使用Java 8的CompletableFuture来优化该方法,如下所示:
```java
public JSONArray getPlayUrl(List<String> ids) throws Exception {
long start = System.currentTimeMillis();
JSONObject user = getToken();
String token = user.getString("token_type") + " " + user.getString("access_token");
JSONArray jsonArray = new JSONArray();
List<CompletableFuture<JSONObject>> futures = new ArrayList<>();
for (String id : ids) {
CompletableFuture<JSONObject> future = CompletableFuture.supplyAsync(() -> {
JSONObject json;
String param = "id=" + id + "&userId=" + user.get("user_id");
json = JSON.parseObject(HttpUtils.doGet(getPlayUrl, param, token));
log.info("中台返回设备流地址url:{}", json.getJSONObject("data"));
return json.getJSONObject("data");
});
futures.add(future);
}
CompletableFuture<Void> allFutures = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
allFutures.join();
for (CompletableFuture<JSONObject> future : futures) {
jsonArray.add(future.get());
}
long end = System.currentTimeMillis();
log.info("同步中台2.0耗时:{}", (end - start));
return jsonArray;
}
```
使用CompletableFuture可以将任务异步执行,从而提高并发处理能力。同时,使用CompletableFuture.allOf()方法可以等待所有异步任务都完成后再执行下一步操作,避免了手动遍历Future对象的等待。
阅读全文