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

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

问题描述

我有以下方法:

public String getResult() {

        List<String> serversList = getServerListFromDB();

        List<String> appList = getAppListFromDB();

        List<String> userList = getUserFromDB();

        return getResult(serversList, appList, userList);
    }

这里我按顺序调用三个方法,然后点击DB并取出我结果,然后我对从DB命中获得的结果进行后处理。我知道如何通过使用 Threads 同时调用这三种方法。但我想使用Java 8 Parallel Stream 来实现这一目标。有人可以指导我如何通过Parallel Streams实现相同的目标吗?

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?

编辑我只想通过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天全站免登陆