完成后的未来和数据采集

时间:2019-06-21 12:15:41

标签: java spring-boot concurrency future executor

请帮助理解。我将查询发送到数据库并获取查询执行时间。

下面是控制器中的方法,其中在请求的主体中传递了一个请求。我创建了一个由3个线程组成的池,在执行程序中调用了3个将请求发送至3个不同基数的方法,并将其全部包装在Future<Map<String, Object>>中,然后在future.get()的帮助下,我等待直到得到来自所有3个流的结果,并将其作为地图返回。

我通过邮递员检查:发送请求时,是时候等待请求了,例如3秒钟之内,我就会得到结果。

提出的问题如下: 1)有必要并行(同时)发送3个碱基的请求 2)有必要禁止重新发送请求,直到从所有3个线程(而不是其中一个)收到结果为止。 例如(第一个线程是空闲的,第二个和第三个线程很忙,我们可以再次对基数执行查询)

@PostMapping(value = "/select/")
public Map<String, Object> callSelectQuery(@RequestBody SelectQuery query) throws InterruptedException, TimeoutException, ExecutionException {

    List<Map<String, Object>> list = new ArrayList<>();

    ExecutorService executor = Executors.newFixedThreadPool(3);

    Future<Map<String, Object>> future = executor.submit(() -> {
        Map<String, Object> mapMySql = mySqlService.select(query);
        Map<String, Object> mapPostgreSQL = postgreSqlService.select(query);
        Map<String, Object> mapH2DB = h2Service.select(query);
        list.add(mapMySql);
        list.add(mapPostgreSQL);
        list.add(mapH2DB);
        return list;
    });

    System.out.println("Future is done? " + future.isDone());

    Map<String, Object> result = future.get(5, TimeUnit.SECONDS);

    System.out.println("Future is done? " + future.isDone());
    System.out.println("result: " + result);

    executor.shutdown();

    return result;
}

这是数据库的三种查询方法之一(我知道执行时间):

public Map<String, Object> select(SelectQuery query) {

    Map<String, Object> map = new HashMap();

    try {
        final Stopwatch sw = Stopwatch.createStarted();
        mysqlTemplate.queryForList(String.valueOf(query));
        sw.stop();
        long executionTime = sw.elapsed(TimeUnit.MILLISECONDS);
        map.put("MySQL execution time: ", executionTime + " ms");
    } catch (EmptyResultDataAccessException e) {
        logger.error("Error select data: " + e.getMessage(), e);
    }

    return map;
}

告诉我,此功能是否正确编写?我是否真的等待它们在3个方法的运行时执行,并且只有当所有3个请求都准备好时,我才能得到Future的结果,并且无法再次发送请求吗?

谢谢!

0 个答案:

没有答案
相关问题