如何检查 Flux<Object> 是否为空?

How to check Flux<Object> is empty or not?

我有一个 api 供 kubernetes 调用并检测服务是否可用或 not.In api,首先调用一个接口来获取其他服务的主机,接口 return一个Flux,如果结果为空api return SERVICE_UNAVAILABLE other return ok.My 当前代码如下:

@GetMapping(value = "/gateway/readiness")
public Mono<Long> readiness(ServerHttpResponse response) {
    Flux<Map<String, List<String>>> hosts = hostProvider.getHosts();
    List<String> hostProviders = new ArrayList<>();
    
    // the below code has a warning: Calling subscribe in a non-blocking scope
    hosts.subscribe(new Consumer<Map<String, List<String>>>() {
        @Override
        public void accept(Map<String, List<String>> stringListMap) {
            hostProviders.addAll(stringListMap.keySet());
        }
    });
    if (hostProviders.isEmpty()) {
        response.setStatusCode(HttpStatus.SERVICE_UNAVAILABLE);
    }
    return routeLocator.getRoutes().count();
}

有优雅做到这一点吗?

你应该像这样重写你的代码:

@GetMapping(value = "/gateway/readiness")
public Mono<ResponseEntity<Long>> readiness() {
    Flux<Map<String, List<String>>> hosts = Flux.empty();
    return hosts
            .flatMapIterable(Map::keySet)
            .distinct()
            .collectList()
            .map(ignored -> ResponseEntity.ok(1L))
            .defaultIfEmpty(ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).build());
}

请尝试以下操作:

@GetMapping(value = "/gateway/readiness")
public Mono<ServerResponse> readiness() {
    return hostProvider.getHosts()
            .map(Map::keySet)
            .flatMap(set -> Flux.fromStream(set.stream()))
            .collectList()
            .flatMap(hostProviders -> 
               // response whatever you want to the client
               ServerResponse.ok().bodyValue(routeLocator.getRoutes().count())
            )
            // if no value was propagated from the above then send 503 response code
            .switchIfEmpty(ServerResponse.status(HttpStatus.SERVICE_UNAVAILABLE).build());
}