通过 Streams 并行执行多个查询 [英] Execute multiple queries in parallel via Streams

查看:52
本文介绍了通过 Streams 并行执行多个查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

public String getResult() {

        List<String> serversList = getServerListFromDB();

        List<String> appList = getAppListFromDB();

        List<String> userList = getUserFromDB();

        return getResult(serversList, appList, userList);
    }

这里我依次调用三个方法,它们依次访问数据库并获取我的结果,然后我对从数据库命中获得的结果进行后期处理.我知道如何通过使用 Threads 来同时调用这三个方法.但我想使用 Java 8 Parallel Stream 来实现这一点.有人可以指导我如何通过并行流实现相同的目标吗?

Here I am calling three method sequentially which in turns hits the DB and fetch me results, then I do post processing on the results I got from the DB hits. I know how to call these three methods concurrently via use of Threads. But I would like to use Java 8 Parallel Stream to achieve this. Can someone please guide me how to achieve the same via Parallel Streams?

EDIT 我只想通过 Stream 并行调用这些方法.

EDIT I just want to call the methods in parallel via Stream.

private void getInformation() {
    method1();
    method2();
    method3();
    method4();
    method5();
}

推荐答案

你可以这样使用CompletableFuture:

public String getResult() {

    // Create Stream of tasks:
    Stream<Supplier<List<String>>> tasks = Stream.of(
            () -> getServerListFromDB(),
            () -> getAppListFromDB(),
            () -> getUserFromDB());

    List<List<String>> lists = tasks
         // Supply all the tasks for execution and collect CompletableFutures
         .map(CompletableFuture::supplyAsync).collect(Collectors.toList())
         // Join all the CompletableFutures to gather the results
         .stream()
         .map(CompletableFuture::join).collect(Collectors.toList());

    // Use the results. They are guaranteed to be ordered in the same way as the tasks
    return getResult(lists.get(0), lists.get(1), lists.get(2));
}

这篇关于通过 Streams 并行执行多个查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆