學(xué)習(xí)使用CompleteFuture

最近遇到一個(gè)需求舅桩,一批數(shù)據(jù),要去請求A B C 多個(gè)接口寨蹋。不同接口返回不同字段的值松蒜。然后設(shè)置到原來的對象中。

其中 A BC 接口每次請求都對數(shù)量有限制已旧。

好了秸苗,使用CompleteFuture來解決

代碼:

    @GetMapping("/user2")
    public List<User> getData() throws Exception {
        List<User> userList = new ArrayList<>(2000);
        for (int j = 0; j < 1000; j++) {
            User u1 = new User();
            u1.setId(j + "");
            u1.setAddress("地址:" + j);
            u1.setAge(j + "");
            userList.add(u1);
        }
        long l = System.currentTimeMillis();
//        getOtherInfo(userList);
//        getUserName(userList);
//        getMobile(userList);

        CompletableFuture<Void> otherTask = CompletableFuture.runAsync(() -> {
            getOtherInfo(userList);
        }, poolExecutor);
        CompletableFuture<Void> nameTask = CompletableFuture.runAsync(() -> {
            getUserName(userList);
        }, poolExecutor);
        CompletableFuture<Void> mobileTask = CompletableFuture.runAsync(() -> {
            getMobile(userList);
        }, poolExecutor);
        try {
            CompletableFuture.allOf(nameTask, mobileTask, otherTask).join();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("================調(diào)用第三方耗時(shí):" + (System.currentTimeMillis() - l) + " 毫秒");
        return userList;
    }

原始請求接口 A B C

    /**
     * 模擬調(diào)用第三方,獲取其他信息
     *
     * @param users
     */
    private void getOtherInfo(List<User> users) {
        long beginTime = System.currentTimeMillis();
        List<List<User>> subUsers = new ArrayList<>();
        List<List<User>> partitionList = getPartitionList(users, subUsers, 50);
//        partitionList.forEach(list -> {
//                sendRequestToService(100);
//                list.forEach(user -> {
//                    user.setBirth("生日: " + user.getId());
//                    user.setSex("性別:" + user.getId());
//            });
//        });
        List<CompletableFuture> futures=new ArrayList<>();
        for (int i = 0; i < partitionList.size(); i++) {
            List<User> list = partitionList.get(i);
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                System.out.println(Thread.currentThread().getName() + " 正在執(zhí)行任務(wù)");
                sendRequestToService(100);
                list.forEach(user -> {
                    user.setBirth("生日: " + user.getId());
                    user.setSex("性別:" + user.getId());
                });
            });
            futures.add(future);
        }
        CompletableFuture allFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
        allFuture.join();
//        System.out.println(Thread.currentThread().getName() + " 正在執(zhí)行任務(wù)");
        System.out.println("獲取其他信息耗時(shí):" + (System.currentTimeMillis() - beginTime) + " 毫秒");
    }

    /**
     * 獲取用戶姓名
     *
     * @param users
     */
    private void getUserName(List<User> users) {
        long beginTime = System.currentTimeMillis();
        List<List<User>> subUsers = new ArrayList<>();
        List<List<User>> partitionList = getPartitionList(users, subUsers, 200);
        partitionList.forEach(list -> {
            sendRequestToService(130);
            list.forEach(user -> {
                user.setUsername("姓名:" + user.getId());
            });
        });

        System.out.println(Thread.currentThread().getName() + " 正在執(zhí)行任務(wù)");
        System.out.println("獲取用戶姓名 耗時(shí):" + (System.currentTimeMillis() - beginTime) + " 毫秒");
    }

    /**
     * 獲取手機(jī)
     * @param users
     */
    private void getMobile(List<User> users) {
        long beginTime = System.currentTimeMillis();
        List<List<User>> subUsers = new ArrayList<>();
        List<List<User>> partitionList = getPartitionList(users, subUsers, 400);
        partitionList.forEach(list -> {
            sendRequestToService(150);
            list.forEach(user -> {
                user.setMobile("手機(jī):" + user.getId());
            });
        });
        System.out.println(Thread.currentThread().getName() + " 正在執(zhí)行任務(wù)");
        System.out.println("獲取用戶姓名 耗時(shí):" + (System.currentTimeMillis() - beginTime) + " 毫秒");
    }

數(shù)據(jù)進(jìn)行分片 和模擬時(shí)間

    /**
     * 根據(jù)分片來獲取數(shù)據(jù)
     *
     * @param users
     * @param subUsers
     * @param count
     * @return
     */
    private List<List<User>> getPartitionList(List<User> users, List<List<User>> subUsers, int count) {
        if (users.size() >= count) {
            subUsers = Lists.partition(users, count);
        } else {
            subUsers.add(users);
        }
        return subUsers;
    }

    /**
     * 根據(jù)傳入時(shí)間來判斷暫停接口多少毫秒
     *
     * @param i
     */
    private void sendRequestToService(int count) {
        try {
            // 模擬請求對面接口count毫秒
            TimeUnit.MILLISECONDS.sleep(count);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Bean
    @Qualifier(value = "MyThread")
    private ThreadPoolTaskExecutor poolExecutor(){
        ThreadPoolTaskExecutor executor =new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(100);
        executor.setKeepAliveSeconds(10);

        executor.setThreadNamePrefix("Pool-Nexus");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

最終結(jié)果:

不使用 future 
http-nio-8009-exec-1 正在執(zhí)行任務(wù)
獲取其他信息耗時(shí):2012 毫秒
http-nio-8009-exec-1 正在執(zhí)行任務(wù)
獲取用戶姓名 耗時(shí):652 毫秒
http-nio-8009-exec-1 正在執(zhí)行任務(wù)
獲取用戶姓名 耗時(shí):454 毫秒
================調(diào)用第三方耗時(shí):3118 毫秒
使用3個(gè)
Pool-Nexus3 正在執(zhí)行任務(wù)
獲取用戶姓名 耗時(shí):453 毫秒
Pool-Nexus2 正在執(zhí)行任務(wù)
獲取用戶姓名 耗時(shí):654 毫秒
Pool-Nexus1 正在執(zhí)行任務(wù)
獲取其他信息耗時(shí):2011 毫秒
================調(diào)用第三方耗時(shí):2014 毫秒

使用3個(gè)再為了獲取其他信息接口再套3個(gè)
ForkJoinPool.commonPool-worker-1 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-2 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-4 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-3 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-5 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-3 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-4 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-2 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-5 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-1 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-3 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-4 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-2 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-1 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-5 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-4 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-2 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-3 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-5 正在執(zhí)行任務(wù)
ForkJoinPool.commonPool-worker-1 正在執(zhí)行任務(wù)
獲取其他信息耗時(shí):406 毫秒
Pool-Nexus3 正在執(zhí)行任務(wù)
獲取用戶姓名 耗時(shí):454 毫秒
Pool-Nexus2 正在執(zhí)行任務(wù)
獲取用戶姓名 耗時(shí):656 毫秒
================調(diào)用第三方耗時(shí):660 毫秒

1個(gè)異步加多個(gè)completeFuture



最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末运褪,一起剝皮案震驚了整個(gè)濱河市惊楼,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌秸讹,老刑警劉巖檀咙,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異嗦枢,居然都是意外死亡攀芯,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進(jìn)店門文虏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來侣诺,“玉大人,你說我怎么就攤上這事氧秘∧暝В” “怎么了?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵丸相,是天一觀的道長搔确。 經(jīng)常有香客問我,道長灭忠,這世上最難降的妖魔是什么膳算? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮弛作,結(jié)果婚禮上涕蜂,老公的妹妹穿的比我還像新娘。我一直安慰自己映琳,他們只是感情好机隙,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布蜘拉。 她就那樣靜靜地躺著,像睡著了一般有鹿。 火紅的嫁衣襯著肌膚如雪旭旭。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天葱跋,我揣著相機(jī)與錄音持寄,去河邊找鬼。 笑死娱俺,一個(gè)胖子當(dāng)著我的面吹牛际看,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播矢否,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼脑溢!你這毒婦竟也來了僵朗?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤屑彻,失蹤者是張志新(化名)和其女友劉穎验庙,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體社牲,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡粪薛,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了搏恤。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片违寿。...
    茶點(diǎn)故事閱讀 39,690評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖熟空,靈堂內(nèi)的尸體忽然破棺而出藤巢,到底是詐尸還是另有隱情,我是刑警寧澤息罗,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布掂咒,位于F島的核電站,受9級特大地震影響迈喉,放射性物質(zhì)發(fā)生泄漏绍刮。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一挨摸、第九天 我趴在偏房一處隱蔽的房頂上張望孩革。 院中可真熱鬧,春花似錦油坝、人聲如沸嫉戚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽彬檀。三九已至帆啃,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間窍帝,已是汗流浹背努潘。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留坤学,地道東北人疯坤。 一個(gè)月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像深浮,于是被迫代替她去往敵國和親压怠。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內(nèi)容