代码之家  ›  专栏  ›  技术社区  ›  Jan Kück

如何避免在等待未来完成时循环?

  •  0
  • Jan Kück  · 技术社区  · 1 年前

    我对java future和处理程序函数有问题。代码示例:

    public HealthCheckResponse call() {
    
      String redisHost = this.configuration.getRedisHost();
      log.info("connect to redis host: {}", redisHost);
      
      Future<RedisConnection> redisConnectionFuture = Redis.createClient(Vertx.vertx(), redisHost).connect();
            while (!redisConnectionFuture.isComplete()) {
                log.debug("waiting for redis connection future complete: ({})", redisConnectionFuture.isComplete());
            }
            log.info("redis connection future completed, {} and succeded {}", redisConnectionFuture.isComplete(), redisConnectionFuture.succeeded());
            if (redisConnectionFuture.isComplete() && redisConnectionFuture.succeeded()) {
                return HealthCheckResponse.up("RedisCustomHealthCheck");
            }
            log.info("sending down RedisCustomHealthCheck");
            return HealthCheckResponse.down("RedisCustomHealthCheck");
        }
    

    所以我的问题是我必须检查redis连接。这是一个异步函数,所以我可以设置onSuccess并编写我的逻辑。在那里我无法返回健康检查响应。问题,我不想等待while循环。这个问题的可能解决方案是什么?

    1 回复  |  直到 1 年前
        1
  •  1
  •   Pendula    1 年前

    如果您没有在vertx事件循环线程上执行此操作,则可以安全地使用 java.util.concurrent.CountDownLatch

    以下是您的用例的一个快速示例:

    public HealthCheckResponse call() {
        Future<RedisConnection> redisConnectionFuture = Redis.createClient(Vertx.vertx(), redisHost).connect();
        CountDownLatch countDownLatch = new CountDownLatch(1);
    
        redisConnectionFuture.onComplete(x -> countDownLatch.countDown());
    
        try {
          countDownLatch.await();
        } catch (InterruptedException e) {
          throw new RuntimeException(e);
        }
    
        if (redisConnectionFuture.succeeded()) {
          return HealthCheckResponse.up("RedisCustomHealthCheck");
        } else {
          return HealthCheckResponse.down("RedisCustomHealthCheck");
        }
      }