Java接口串行查询改成并行查询,使用CompletableFuture并行异步处理

1.串行接口示例 controller层

    /**
     * @Description:方法描述
     * @Param: 串行接口
     * @return:
     * @date: 2022/11/3
     * @version 1.0
     */
    @GetMapping("/testTask")
    public Map<Object, Object> testTask() throws Exception {
        HashMap<Object, Object> map = new HashMap<>();
        long l = System.currentTimeMillis();

        String s1 = testTaskService.testTask1();
        map.put("s1", s1);
        String s2 = testTaskService.testTask2();
        map.put("s2", s2);
        String s3 = testTaskService.testTask3();
        map.put("s3", s3);
        long l1 = System.currentTimeMillis();
        System.out.println("串行接口用时:" + (l1 - l) / 1000 + "秒");
        return map;
    }

2.并行接口示例 controller层

  /**
     * @Description:方法描述
     * @Param:
     * @return:并行接口优化
     * @date: 2022/11/3
     * @version 1.0
     */
    @GetMapping("/testTask2")
    public Map<Object, Object> testTask2() throws Exception {
        HashMap<Object, Object> map = new HashMap<>();
        long l = System.currentTimeMillis();

        // supplyAsync    runAsync
        CompletableFuture.allOf(
                CompletableFuture.runAsync(() -> {
                    map.put("s1", testTaskService.testTask1());
                }, ForkJoinPool.commonPool()),
                CompletableFuture.runAsync(() -> {
                    map.put("s2", testTaskService.testTask2());
                }, ForkJoinPool.commonPool()),
                CompletableFuture.runAsync(() -> {
                    map.put("s3", testTaskService.testTask3());
                }, ForkJoinPool.commonPool())
        ).join();

        long l1 = System.currentTimeMillis();
        System.out.println("并行接口用时:" + (l1 - l) / 1000 + "秒");
        return map;
    }

模拟接口查询接口速度

@Service
public class TestTaskService {


    public String testTask1()  {
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "testTask1";
    }

    public String testTask2()  {
        try {
            Thread.sleep(2 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "testTask2";
    }

    public String testTask3() {
        try {
            Thread.sleep(5 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "testTask5";
    }

}

执行结果:

串行接口用时:9秒 正好是每个接口所花费的时间总和(2+2+5)

并行接口用时:5秒 是几个接口中花费时间最长的一个时间点 5

串行接口改并行接口,接口查询速度快了好多!

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值