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

问题描述 投票:0回答: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 并编写我的逻辑。我无法返回 HealtCheckResponse。问题,我不想用 while 循环等待。这个问题的可能解决方案是什么?

java redis quarkus future vert.x
1个回答
0
投票

既然你有 Future 对象,你可以使用类似的东西:

redisConnectionFuture.onSuccess(connection -> {
    log.info("redis connection future completed, {} and succeded {}", redisConnectionFuture.isComplete(), redisConnectionFuture.succeeded());
    // You can access the connection object here
    return HealthCheckResponse.up("RedisCustomHealthCheck");
}).onFailure(failure -> {
    log.error("redis connection failed", failure);
    return HealthCheckResponse.down("RedisCustomHealthCheck");
});
© www.soinside.com 2019 - 2024. All rights reserved.