针对于具体的业务场景,现在场景要求如下:
现在需要统计不同维度的数据,且数据之间没有耦合关系,如果用传统的思路一条一条执行sql语句,执行效率比较忙,这里的思路是多开几条异步线程去处理,查询数据,最后将数据进行封装返回给前端,使用到的有自定义
异步线程任务(
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3,5,2L, TimeUnit.SECONDS,new LinkedBlockingQueue<>(3));
)、线程池(
CompletableFuture.runAsync(()->{ String temperature = qzStorageMapper.selectTemperature(entCode,storageName); qzStoDcsVo.setTemperature(StringUtils.isEmpty(temperature)==true?"0":temperature); countDownLatch.countDown(); },threadPool);
)、线程执行完成标志做减法(
CountDownLatch
)
代码效果如下:
//当三个线程都执行完毕的时候,返回前端数据
CountDownLatch countDownLatch=new CountDownLatch(3);
//创建线程池
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3,5,2L,
TimeUnit.SECONDS,new LinkedBlockingQueue<>(3));
try{
CompletableFuture.runAsync(()->{
String temperature = qzStorageMapper.selectTemperature(entCode,storageName);
qzStoDcsVo.setTemperature(StringUtils.isEmpty(temperature)==true?"0":temperature);
countDownLatch.countDown();
},threadPool);
CompletableFuture.runAsync(()->{
String pressure = qzStorageMapper.selectPressure(entCode,storageName);
qzStoDcsVo.setPressure(StringUtils.isEmpty(pressure)==true?"0":pressure);
countDownLatch.countDown();
},threadPool);
CompletableFuture.runAsync(()->{
String liquid = qzStorageMapper.selectLiquid(entCode,storageName);
qzStoDcsVo.setLiquid(StringUtils.isEmpty(liquid)==true?"0":liquid);
countDownLatch.countDown();
},threadPool);
countDownLatch.await();
}catch(Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
使用异步处理和不使用异步处理的用时时间前后对比:
使用前:
由图可以看出稳定之后基本在8-9毫米
使用后:
由图可以看出耗时基本在2-4毫米区间,速度提升两倍多一些,看似提升效果不大,但经不起请求数量多,那也是一笔不小的性能提升