Search code examples
spring-bootspring-cloudspring-webclient

Retrieve webclient response - Spring Cloud


I'm using spring cloud to request data from another service. So, basically I request data and I want to retrieve that data and assigns it to another object which will be the one I'll save.

This is my code:

public Mono<Shops> save(Shops shops) {

    Mono<Shops> s = webClientBuilder.build().get()
            .uri("http://mysql-app/api/reservation-passengers/boarding-pass-data/" + shops.getBoardingPassId().toString())
            .exchange()
            .flatMap(response -> {
                Shops myShops = response.bodyToMono(Shops.class).block();
                shops.setAirportDestiny(myShops.getAirportDestiny());
                shops.setCustomerId(myShops.getCustomerId());
                return shopsRepository.save(shops);
            });
    return s;   
}

However I got an exception:

java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-7

How can I get data from a asynchronous method?


Solution

  • I got a solution. I had to change my code a little bit.

    public Mono<Shops> save(Shops shops) {
        Mono<BoardingPassDTO> response = webClientBuilder.build().get()
                .uri("http://mysql-app/api/reservation-passengers/boarding-pass-data/" 
                        + shops.getBoardingPassId().toString())
                .retrieve().bodyToMono(BoardingPassDTO.class);
    
        return response.flatMap(r ->{
                shops.setAirportDestiny(r.getAirportArrivalId());
                shops.setCustomerId(r.getPassengerId());    
                shops.setShopDate(LocalDateTime.now());
                return shopsRepository.save(shops);
            });     
    }