Search code examples
javaspringspring-bootspring-webfluxreactor

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


I have a api for kubernetes to call and detect service is available or not.In the api,first call a interface to get host of other service,the interface return a Flux,if the result is empty api return SERVICE_UNAVAILABLE other return ok.My current code as below:

@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();
}

Has graceful to do this?


Solution

  • Please, try the following:

    @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());
    }