Spring Webclient : Non-blocking, reactive client to perform HTTP operations

Dhiraj Surve
1 min readDec 31, 2021
  • Webclient provide asynchronous,non-blocking way to communicate with different system using http operations .
  • This is not replacement for RestTemplate however its to improve performance of operations and avoid blocking thread to wait for response .
  • Webclient fires the operation and does not wait for response which make the call reactive and process the response when its received .

Asynchronous web frameworks apply event looping to handle more requests with fewer threads.

Maven Dependency

<dependency> 
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

Code Implementation:

  • GET:
UriCimponenets uriComponents =UriComponentsBuilds.fromHttpUrl(“http://endpoint/{param}")
.buildAndExpand(inputParam);
HttpHeaders headers= new HttpHeaders ();
Webclient webclient;
String response=webclient.method(HttpMethod.GET)
.uri (uriComponents.toUri())
.headers(httpHeaders-> {
httpHeaders.add(“key”,”value”);
})
.contentType(MediaType.APPLICATION_JSON)
.retrieve()
.onStatus(status-> status.is4xxClientError|| status.5xxClientError(),
clientResponse-> {clientResponse.bodyToMono(String.class).subscriber(errorBody->log.error(error.Body));
return Mono.Error(new ResponseStatusException(clientResponse.statusCode()));
})
.bodyToMono(String.class)
.doOnSuccess(clientResposne -> { log.info(“Response: {}”,clientResponse)})
.block(Duration,ofSeconds(50));

POST:

UriCimponenets uriComponents =UriComponentsBuilds.fromHttpUrl(“http://endpoint/{param}")
.buildAndExpand(inputParam);
HttpHeaders headers= new HttpHeaders ();
Webclient webclient;
//post response status of operation .
String response=webclient.method(HttpMethod.POST)
.uri (uriComponents.toUri())
.headers(httpHeaders-> {
httpHeaders.add(“key”,”value”);
})
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromValue(<jsonStringBody>))
.exchange()
.flatMap(clientResponse -> {
if(clientResponse.statusCode().is4xxClientError())
{
clientResponse-> {clientResponse.bodyToMono(String.class).subscriber(errorBody->log.error(error.Body));
return Mono.Error(new ResponseStatusException(clientResponse.statusCode()));
}
else
return clientResponse.bodyToMono(String.class); })
.doOnSuccess(clientResposne -> { log.info(“Response: {}”,clientResponse)})
.block(Duration,ofSeconds(50));

ref# https://livebook.manning.com/book/spring-in-action-fifth-edition/chapter-11/v-7/33

--

--