CompletableFuture 提高接口的响应速度

1. 业务需求,获取各个模块的消息数量

2. 如果接口使用顺序执行,需要等待所有的消息数量查询完成后返回,耗时为各模块耗时的总和

如:

/**
     * 消息提示
     *      技术通告:通告未读数
     *      系统公告:公告的未读数
     *      在线反馈:反馈回复但未读数
     * @param currentUser
     * @return
     */
    @MsgTranslate
    @RequestMapping("/msg")
    public Result promptMessage(@CurrentUser UserDto currentUser){

        // 技术通告 未读数
        Long unread1 = bulletinService.unread(currentUser);

        // 系统公告未读数
        Long unread2 = sysNoticeService.unread(currentUser);

        // 在线反馈 未读数
        Long unread3 = feedbackService.unread(currentUser);

        Map<String, Long> map = new HashMap<>();
        map.put(EnumConstant.MENU_SYS_NOTIC_CODE, unread2);
        map.put(EnumConstant.MENU_SYS_BULLETIN_CODE, unread1);
        map.put(EnumConstant.MENU_SYS_FEEDBACK_CODE, unread3);

        return Result.success(map);
    }

 3. 使用异步查询【CompletableFuture】,等待所有线程查询后返回结果,耗时为各模块中耗时最大的时间

如:

 /**
     * 核心线程 8 最大线程 20 保活时间30s 存储队列 10 有守护线程 拒绝策略:将超负荷任务回退到调用者
     */
    private static ExecutorService executor = new ThreadPoolExecutor(20, 50, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(100), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());


    /**
     * 消息提示
     *      技术通告:通告未读数
     *      系统公告:公告的未读数
     *      在线反馈:反馈回复但未读数
     * @param currentUser
     * @return
     */
    @MsgTranslate
    @RequestMapping("/msg")
    public Result promptMessage(@CurrentUser UserDto currentUser){

        // 技术通告 未读数
        CompletableFuture<Long> bulletinFT = CompletableFuture.supplyAsync(() -> bulletinService.unread(currentUser), executor);
        // 系统公告 未读数
        CompletableFuture<Long> noticeFT = CompletableFuture.supplyAsync(() -> sysNoticeService.unread(currentUser), executor);
        // 在线反馈 未读数
        CompletableFuture<Long> feedbackFT = CompletableFuture.supplyAsync(() -> feedbackService.unread(currentUser), executor);

        Map<String, Long> map = new HashMap<>();
        try {
            // 聚合所有的查询 等所有的查询都查询完 最多等10秒
            CompletableFuture.allOf(bulletinFT, noticeFT, feedbackFT).get(10, TimeUnit.SECONDS);

            map.put(EnumConstant.MENU_SYS_NOTIC_CODE, noticeFT.get());
            map.put(EnumConstant.MENU_SYS_BULLETIN_CODE, bulletinFT.get());
            map.put(EnumConstant.MENU_SYS_FEEDBACK_CODE, feedbackFT.get());
        } catch (Exception e) {
            map.put(EnumConstant.MENU_SYS_NOTIC_CODE, 0);
            map.put(EnumConstant.MENU_SYS_BULLETIN_CODE, 0);
            map.put(EnumConstant.MENU_SYS_FEEDBACK_CODE, 0);
        }

        return Result.success(map);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值