【问题标题】:How to get the object from Mono<Object>如何从 Mono<Object> 获取对象
【发布时间】:2021-09-24 11:19:54
【问题描述】:

我正在使用 WebClient 与其他微服务进行通信。我想通过 id 从远程 UserService 获取用户,然后我想将此用户信息发送到另一个远程服务问题是我以 Mono 形式获得响应,但我必须将其作为 User 对象获取。我试过 block() 但它没有用它总是抛出这个错误:java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread 这是代码

    public User findUserById(String user_id){
        return webClientBuilder.build().get().uri("http://localhost:7854/"+user_id)
                .retrieve().onStatus(httpStatus -> HttpStatus.NOT_FOUND.equals(httpStatus),clientResponse -> Mono.empty())
                .bodyToMono(User.class).block();
    }

我正在使用 春季启动 2.5.4 Java 11

【问题讨论】:

  • 你想用User 对象做什么?你能添加一些代码吗?有几个选项可以做到这一点,但这真的取决于你的用例。
  • 我只想获取该用户,然后在发布请求中将其发送到另一个服务

标签: java spring-boot reactive-programming spring-webclient


【解决方案1】:

假设调用其他服务的方法如下:

public Mono<Whatever> callToAnotherService(User user){
    // your logic here, I am assuming this is a WebClient call also.
}

并且您将上述方法更改为:

public Mono<User> findUserById(String user_id){
    return webClientBuilder.build().get().uri("http://localhost:7854/"+user_id)
            .retrieve().onStatus(httpStatus -> HttpStatus.NOT_FOUND.equals(httpStatus),clientResponse -> Mono.empty())
            .bodyToMono(User.class);
}

您现在可以在调用findUserByIdcallToAnotherService 的类中执行以下操作:

findUserById("userId").flatMap(user -> callAnotherService(user)).subscribe();

【讨论】:

  • 非常感谢您做得很好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-07
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多