利用多线程+countDownluanch 优化查询接口提升效率10倍以上
最近在做工单系统的生产调优,客户想要单子秒出
花了一天时间定位问题,发现查询MySQL、Mongo、Redis 查询耗时都很小,在0~4ms
耗时较大的是一段给 activity 中 form 的 field 设置属性的遍历
有一段 activities.forEach(activity -> {}),循环中有两个嵌套,一个两层,一个三层,逻辑上不好拆分
于是采用多线程+countdownlaunch,把每次循环通过线程发出去,原有逻辑放到 Runnable 的 run 方法中
countdownlaunch卡住主线程,等待所有并行线程执行完毕
大大降低消耗时间,测试工单查询调用该方法的耗时由原先的 1.2s 降低至 120ms
CountDownLatch countDownLatch = new CountDownLatch(activities.size());
activities.forEach(activity -> { AssembleForm assembleForm = new AssembleForm(activity, forms, fields, countDownLatch); Thread thread = new Thread(assembleForm); thread.start(); }); try { countDownLatch.await(); } catch (InterruptedException e) { log.error("countDownLaunch error: {}", e.getMessage()); } public class AssembleForm implements Runnable{ private List<Form> forms; private List<Field> fields; private Activity activity; private CountDownLatch countDownLatch; AssembleForm(Activity activity, List<Form> forms, List<Field> fields, CountDownLatch countDownLatch){ this.activity = activity; this.forms = forms; this.fields = fields; this.countDownLatch = countDownLatch; } @Override public void run() { // 原有逻辑 codes... countDownLatch.countDown(); } }
论读书
睁开眼,书在面前 闭上眼,书在心里
睁开眼,书在面前 闭上眼,书在心里