Spring Webclient : Non-blocking, reactive client to perform 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:

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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Ubuntu 20.04 on HP 15s-du00094tu — A review from noob!

APPLICATION OF DJIKSTRA’S ALGORITHM IN GOOGLE MAPS

Kotlin: How Lazy Initialization Internally Works

AndroidMakers 2019 randome notes

Flux Node Halving Post Mortem

Apache Kafka. MacOS installation guide.

A Complete MQTT+ESP32 Sensor Tutorial

Pulling It All Together

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dhiraj Surve

Dhiraj Surve

More from Medium

Spring AOP — Using Java annotation as pointcut expressions

Deep dive into Pattern Matching for Java

Your Domain’s Spring Boot Parent POM

How I used a custom permission evaluator in Spring?