如何检查flux object是否为空?

v7pvogib  于 2021-07-05  发布在  Java
关注(0)|答案(2)|浏览(857)

我有一个api供kubernetes调用,检测服务是否可用,在这个api中,首先调用一个接口获取其他服务的主机,接口返回一个流量,如果结果为空api返回服务\u unavailable other return ok,我的当前代码如下:

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

有什么办法吗?

myzjeezk

myzjeezk1#

请尝试以下操作:

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

7vux5j2d2#

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

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

相关问题