提升查询车辆信息速度:使用多线程优化地址转换
<p>@GetMapping("/queryCarsByCoachID")
public Result<Object> queryCarsByCoachID(Coach coach, HttpServletRequest request) {</p>
<pre><code>//权限验证
String token = (String)request.getAttribute("claims_coach");
if(token == null || "".equals(token)){
throw new RuntimeException("权限不足!");
}
//把查询到的的对象放入map集合
Map<String,Object> map = new HashMap<>();
//调用方法查询出设备
List<DeviceEntityDto> deviceEntityDtoList = coachService.queryDeviceEntitiesByCoachIdAndCarModel(coach.getCoachId());
// 创建一个线程池
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
// 创建一个CountDownLatch,用于线程同步
CountDownLatch countDownLatch = new CountDownLatch(deviceEntityDtoList.size());
for (DeviceEntityDto deviceEntityDto : deviceEntityDtoList){
executorService.execute(() -> {
//获得此车辆的地址经纬度
if (!StringUtils.isEmpty(deviceEntityDto.getArea())){
Map<String,String> addressMap = tengXunMapService.getLongitudeAndLatitudeByAddress(deviceEntityDto.getArea());
if (!CollectionUtils.isEmpty(addressMap)){
deviceEntityDto.setLongitude(addressMap.get("lng"));
deviceEntityDto.setLatitude(addressMap.get("lat"));
}
}
//游戏端传递当前设备状态,显示状态(工作中/休息中)
boolean existUser = ExternalCommunicationKit.existUser(deviceEntityDto.getDeviceId());
deviceEntityDto.setWorkStatus(existUser ? 1 :0);
// 线程执行完毕后,计数减一
countDownLatch.countDown();
});
}
try {
// 等待所有线程执行完毕
countDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 关闭线程池
executorService.shutdown();
}
map.put("deviceEntities",deviceEntityDtoList);
//查询到学员传给前端
log.info("查询车辆成功!");
return new Result<>(ResultCode.SUCCESS,map);
</code></pre>
<p>}</p>
原文地址: https://www.cveoy.top/t/topic/qeqd 著作权归作者所有。请勿转载和采集!