需求描述

  • 调用第三方接口,每个需要7秒钟,有时会调用7次左右导致查询很慢,想实现多线程调用并合并结果返回给前端

代码

    public ResponseEntity<WebResult> queryEnterpriseBill() {

        GetBillListResp getBillListResp = null;

        //获取用户下所有custCode
        List<String> custCodes = {"","",""};

        //多线程调用接口
        // 定义线程池
        ExecutorService executorService = Executors.newFixedThreadPool(custCodes.size());

        // 通过异步的方式获取所有信息
        System.out.println("开始获取信息...");
        List<Future> tasks = new ArrayList<>();
        for (String custCode : custCodes){
            // 创建任务,将任务添加到 tasks 中
            tasks.add(getData(custCode));
        }
        // 遍历 tasks,处理每一个 task
        for (Future task : tasks) {
            try {
getBillListResp.getBillList().addAll(((GetBillListResp) task.get()).getBillList());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        tasks.clear();
        System.out.println("结束获取信息...");
        // 关闭线程池
        executorService.shutdown();

        return ResponseEntity.ok(WebResult.of(getBillListResp));
    }


    /**
     * 获取该 task 执行的信息
     * @param executorService
     * @param param
     * @return
     */
    public  Future<GetBillListResp> getData(ExecutorService executorService, String  custCode) {
        return executorService.submit(()->{
            GetBillListResp getBillList = null;
            try {
                //具体调用逻辑
                return getBillList;
            } catch (Exception e) {
                log.error("访问资源错误" + e.getMessage());
                return null;
            }
        });
    }

大概流程就是这样,业务做了删减

参考链接:https://blog.csdn.net/awen6666/article/details/108425177