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

What is Localization? All you Need to Know

Mind your language!

Open Source Software Product Development, Building DDTJ — Day 1

It’s time this cop met the public! 🚨

Dynamic Home Route in a Flutter App

Which One is Better? Native Apps Vs. Hybrid Apps

Where to Start Coding: The First Milestone Towards Success

Python’s Data Classes a Data Engineer’s best friend

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

Dynamically route to read-only and read-write database instances in spring-boot

Checking performance of different SSL/TLS implementations for Java Applications

JUnit5: Parallelization of Parameterized Tests (Only)

JUnit5 Parallelization Configurations

Using the Spring Web Scopes, Part 2