现状

​ /api/xxx/xxx/detail 接口是房源详情的接口,里面聚合了各类信息,比如房源基础信息、房源活动信息、带看统计信息等。类似淘宝商品详情页,会有商品的基础属性、优惠活动、图片、介绍、评价等模块的信息。

目前接口中会查询数据库,并使用 HTTP 请求调用了多个第三方服务获取各个模块信息,各个调用之间采用的是顺序执行,总耗时较长。

优化前使用 Jmeter 测试(10个线程 循环500次)结果如下:

研发环境优化前2.jpg

优化方案

​ 调用多个第三方服务接口之间并没有相互依赖关系,考虑使用多线程并发调用第三方接口,这样可以大大减少总耗时。

并发调用.jpg

代码思路:

    private void packageExtInfoParallel(Object xxx) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(8);
        CountDownLatch countDownLatch = new CountDownLatch(8);

        //处理统计信息  可并发获取
        executorService.submit(() -> {
            try {
                packageFollowStatistics(xxx);
            } finally {
                countDownLatch.countDown();
            }
        });

        executorService.submit(() -> {
            try {
                packageAppointStatistics(xxx);
            } finally {
                countDownLatch.countDown();
            }
        });

        executorService.submit(() -> {
            try {
                packageShelfStatistics(xxx);
            } finally {
                countDownLatch.countDown();
            }
        });

        //并发获取
        executorService.submit(() -> {
            try {
                packageActivityInfo(xxx);
            } finally {
                countDownLatch.countDown();
            }
        });

        //并发取
        executorService.submit(() -> {
            try {
                packageEmptyAppointData(xxx);
            } finally {
                countDownLatch.countDown();
            }
        });

        //并发取
        executorService.submit(() -> {
            try {
                packageShareInfo(xxx);
            } finally {
                countDownLatch.countDown();
            }
        });

        //并发取
        executorService.submit(() -> {
            try {
                packageJcData(xxx);
            } finally {
                countDownLatch.countDown();
            }
        });

        //并发取
        executorService.submit(() -> {
            try {
                packageVerifyCode(xxx);
            } finally {
                countDownLatch.countDown();
            }
        });
        countDownLatch.await();
        executorService.shutdown();
    }

优化结果

​ 总体来说,效果很明显的,P95、P99 提升 50%,有待观察线上效果。

研发环境优化后3.jpg