Springboot : How to use WebClient instead of RestTemplate for Performing Non blocking and Asynchronous calls

前端 未结 3 1951
无人及你
无人及你 2021-02-15 01:18

I have a springboot project which uses Springboot Resttemplate. We have moved to springboot 2.0.1 from 1.5.3 and we are trying to make the rest calls from it asynchronous by us

3条回答
  •  不知归路
    2021-02-15 01:59

    The first step is to build WebClient object with the baseUrl;

    WebClient webClient = WebClient.builder()
        .baseUrl("http://localhost:8080/api") //baseUrl
        .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
        .build();
    

    Then choose the method and append the path along with the request variables or body payload.

    ResponseSpec responseSpec = webClient
        .get()
        .uri(uriBuilder -> uriBuilder.path("/findById") //additional path
            .queryParam("id", id).build())
        .retrieve()
        .onStatus(HttpStatus::is4xxClientError, response -> Mono.error(new CustomRuntimeException("Error")));
    

    Wait for the response with block() function of bodyToMono. If you want response as String, you can convert it using google's gson library.

    Object response = responseSpec.bodyToMono(Object.class).block();
    Gson gson = new Gson();
    String str = gson.toJson(response);
    

    If you don't want to need to know the status of the api call, you can do like following.

    webClient
        .post()
        .uri(uri -> uri.path("/save").build())
        .body( BodyInserters.fromObject(payload) )
        .exchange().subscribe();
    

提交回复
热议问题