【问题标题】:How to make blocking call for Mono?如何对 Mono 进行阻塞调用?
【发布时间】:2023-01-09 19:20:18
【问题描述】:

我的任务是 - 获取 JWT 令牌。(所有详细信息都在这里How to get jwt token value in spring webflux? (to exchange it with Minio STS token)

但是让我们丢弃多余的细节。简而言之:

我有一个源代码:

Mono<Object> mono = ReactiveSecurityContextHolder.getContext()
        .map(securityContext -> securityContext.getAuthentication().getPrincipal());
mono.block(); //<-- I need to get the result of Mono execution HERE at this thread in a blocking manner

我在这里得到错误:

block()/blockFirst()/blockLast() are blocking, which is not supported in thread parallel-2

因为在 reactor 和 bla bla bla 中禁止使用阻塞调用,尽管在以前版本的 reactor 中这段代码是有效的。

我开始寻找问题的解决方案并创建了 2 个主题:

  1. How to get jwt token value in spring webflux? (to exchange it with Minio STS token)
  2. How to get raw token from ReactiveSecurityContextHolder?

    我有一个 advicehere 描述的方式进行阻塞调用:

    所以我的尝试是:

    尝试 1:

    Mono<Object> mono = ReactiveSecurityContextHolder.getContext()
                .map(securityContext -> securityContext.getAuthentication().getPrincipal());
    Mono<Object> objectMono = mono.subscribeOn(Schedulers.boundedElastic());
    Object result = objectMono.block();
    

    尝试 2:

    Mono<Object> mono = ReactiveSecurityContextHolder.getContext()
                .map(securityContext -> securityContext.getAuthentication().getPrincipal());
    mono.subscribeOn(Schedulers.boundedElastic());
    Object result = mono.block();
    

    在这两种情况下,我都会收到相同的错误:

    block()/blockFirst()/blockLast() are blocking, which is not supported in thread parallel-2
    

    我该如何解决?

【问题讨论】:

    标签: java spring-boot spring-security spring-webflux reactor


    【解决方案1】:

    subscribeOn 仅适用于订阅事件,即当您首次添加订阅时。事件仍然发布在默认的调度程序上,在本例中为“并行”。

    为了能够进行阻塞调用,您需要 publishOn 一个非阻塞调度程序,例如:

    Mono<Object> mono = ReactiveSecurityContextHolder.getContext()
                .map(securityContext -> securityContext.getAuthentication().getPrincipal());
    Mono<Object> objectMono = mono.subscribeOn(Schedulers.boundedElastic())
                                  .publishOn(Schedulers.boundedElastic()); // <- this
    
    Object result = mono.block();
    

    应该做的伎俩。

    【讨论】:

    • 我复制粘贴了你的代码,结果与我的问题相同:block()/blockFirst()/blockLast() are blocking, which is not supported in thread parallel-1 我也尝试用 Object result = objectMono .block(); 替换 Object result = mono.block(); 但我仍然看到同样的错误。我该如何解决?
    猜你喜欢
    • 1970-01-01
    • 2020-02-16
    • 2014-03-23
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2017-10-03
    相关资源
    最近更新 更多