Home > Blockchain >  How to get the object from Mono<Object>
How to get the object from Mono<Object>

Time:09-24

I am using WebClient to communicate with other microservices. I want to get user from a remote UserService by id then I want to send this user information to another remote service the problem is I get the response as Mono but I have to get it as User object. i tried block() but it didn't work it always throws this error :java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread here is a code

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

I am using Spring Boot 2.5.4 Java 11

CodePudding user response:

Assuming the call to the other service is done in the following method:

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

And that you change the mentioned method to:

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

You can now do the following in the class that calls both findUserById and callToAnotherService:

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