switchIfEmpty 在之前的 flatMap 返回 Mono.error() 时执行

问题描述 投票:0回答:1

我有一个带有类似代码的 Spring Gateway 过滤器:

public Mono<Something> example{
return redisTemplate.opsForValue()
        .get(cacheKey)
        .flatMap(this::throwMono)        
.switchIfEmpty(somethingElse(cacheKey, token));
}
private Mono<Something> throwMono(String jsonString) {
      return Mono.error(new RuntimeException("oops"));
    
  }

我认为这会导致流程以异常结束,但 switchIfEmpty 在发生异常时始终运行。

我希望返回 Mono.error() 并且 switchIfEmpty 在 flatMap 出现异常时不会运行。

spring-webflux project-reactor spring-cloud-gateway
1个回答
0
投票

实际返回的是Mono.error。

somethingElse
方法只是因为你显式调用它而运行,但返回的 Mono 并未被订阅或执行。

考虑修改后的示例:

public static void main(String[] args) {
    Mono.just("initial")
            .flatMap(s -> Mono.error(new RuntimeException("oops")))
            .switchIfEmpty(somethingElse())
            .subscribe(s -> System.out.println("Success: " + s), Throwable::printStackTrace);
}

private static Mono<String> somethingElse() {
    System.out.println("somethingElse run");
    return Mono.fromCallable(() -> {
                System.out.println("run else Mono");
                return "else";
            })
            .doOnSubscribe(c -> System.out.println("else Mono subscribed"));
}

结束于

运行其他的东西
java.lang.RuntimeException:哎呀
...

没有“运行其他Mono”或“其他Mono订阅”

© www.soinside.com 2019 - 2024. All rights reserved.