DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • How To Build Web Service Using Spring Boot 2.x
  • How to Transform Any Type of Java Bean With BULL
  • Using the Chain of Responsibility Design Pattern in Java

Trending

  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Building Resilient Networks: Limiting the Risk and Scope of Cyber Attacks
  • Building Resilient Identity Systems: Lessons from Securing Billions of Authentication Requests
  1. DZone
  2. Coding
  3. Languages
  4. Reactive Programming in Java: Using the WebClient Class

Reactive Programming in Java: Using the WebClient Class

WebClient is the equivalent of the RestTemplate class — except it works with asynchronous requests.

By 
Jesus J. Puente user avatar
Jesus J. Puente
·
Aug. 28, 19 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
61.1K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we will talk about the WebClient class found in the Spring Boot framework. You can access the source code for this article here. 

This class would be the equivalent of the RestTemplate class, but it works with asynchronous requests.

If you want to use this class, you should put these dependencies in your Maven file.

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

This is also why you need to use WebFlux, which is available in version 5 of Spring. Remember that this version of Spring requires Java 8 or higher.

With WebFlux, which is based on Project Reactor, you can write reactive applications. This kind of application is characterized because the requests aren't blocking and functional programming is widely used.

If you want to understand this article, you need basic prior knowledge about the Reactor and the Mono class. Although, if you have used Streams in Java, you may think that a Mono object is like a Stream that can emit a value or an error.

But I am not going to delve into these issues because they are beyond the scope of this article. It would be sufficient to say that when using the WebClient class, you can make several calls in parallel, so if each request is answered in 2 seconds and you make 5 calls, you can get all the answers in just over 2 seconds, instead of 10.

Parallel Request

In this example project, I have written a server and a client. The server will be running in the 8081 port, and the client will listen in the 8080 port.

This is the code that executes the server application.

@SpringBootApplication
public class WebServerApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(WebServerApplication.class).
properties(Collections.singletonMap("server.port", "8081")).run(args);
}
}

If you make a request to http://localhost:8080/client/XXX, the function testGet will be executed.

@RestController()
@RequestMapping("/client")
@Slf4j
public class ClientController {
final String urlServer="http://localhost:8081";

@GetMapping("/{param}")
public Mono<ResponseEntity<Mono<String>>> testGet(@PathVariable String param) {
final long dateStarted = System.currentTimeMillis();

WebClient webClient = WebClient.create(urlServer+"/server/");
Mono<ClientResponse> respuesta = webClient.get().uri("?queryParam={name}", param).exchange();
Mono<ClientResponse> respuesta1 = webClient.get().uri("?queryParam={name}","SPEED".equals(param)?"SPEED":"STOP").exchange();

Mono<ResponseEntity<Mono<String>>> f1 = Mono.zip(respuesta, respuesta1)
.map(t -> {
if (!t.getT1().statusCode().is2xxSuccessful()) {
return ResponseEntity.status(t.getT1().statusCode()).body(t.getT1().bodyToMono(String.class));
}
if (!t.getT2().statusCode().is2xxSuccessful()) {
return ResponseEntity.status(t.getT2().statusCode()).body(t.getT2().bodyToMono(String.class));
}
return ResponseEntity.ok().body(Mono.just(
"All OK. Seconds elapsed: " + (((double) (System.currentTimeMillis() - dateStarted) / 1000))));
});
return f1;
}

This is a simple controller that performs two requests to the URL http://localhost:8081. In the first request, the parameter passed is the function received in the param variable. In the second, the sentence "STOP" is sent if the param variable is different from the word SPEED.

The server upon receiving the parameter "STOP" will wait 5 seconds and then will answer.

From the moment we create the instance of the class WebClient, I specify the URL of the request.

WebClient webClient = WebClient.create(urlServer+"/server/");

Then, it executes the call of the type GET to the server passing the parameter QueryParam. In the end, when executing the function exchange, it will receive a Mono object containing a ClientResponse class that is equivalent to the ResponseEntity object of the RestTemplate class. The class ClientResponse will have the HTTP code, the body, and the headers sent by the server.

Mono<ClientResponse> respuesta = webClient.get().uri("?queryParam={name}", param).exchange();

Wait a minute...

Did I say it will execute? Well, I lied. Really only what I want to do has been declared. In reactive programming, until someone does not subscribe to a request, nothing is executed, so the request to the server has not yet been made.

On the next line, the second request to the server is defined.

Mono<ClientResponse> respuesta1 = webClient.get()
  .uri("?queryParam={name}","SPEED".equals(param)?"SPEED":"STOP").exchange();

Finally, a Mono object is created, which will be the result of the previous two, using the zip function.

Using the map function, a ResponseEntity object with the HTTP code equal to OK will be returned if the two requests have answered a 2XX code; otherwise, the code and answer of the server will be returned.

Being WebClient-reactive, the two requests are realized simultaneously, and therefore, you will be able to see that if you execute this code: curl http://localhost:8080/client/STOP, you have the answer in just over 5 seconds, even if the sum of the call time is greater than 10 seconds.

 All OK. Seconds elapsed: 5.092

A POST request

In the testURLs function, there is an example of a call using POST.

This function receives a Map in the body that will then be placed in the request headers. In addition, this map will be sent in the body of the request that will be made to the server.

@PostMapping("")
public Mono<String> testURLs(@RequestBody Map<String,String> body,
@RequestParam(required = false) String url) {

log.debug("Client: in testURLs");
WebClient.Builder builder = WebClient.builder().baseUrl(urlServer).
defaultHeader(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_JSON_VALUE);
if (body!=null && body.size()>0 )
{
for (Map.Entry<String, String> map : body.entrySet() )
{
builder.defaultHeader(map.getKey(), map.getValue());
}
}
WebClient webClient = builder.build();
String urlFinal;
if (url==null)
urlFinal="/server/post";
else
urlFinal="/server/"+url;

Mono<String> respuesta1 = webClient.post().uri(urlFinal).body(BodyInserters.fromObject(body)).exchange()
.flatMap( x -> 
{ 
if ( ! x.statusCode().is2xxSuccessful())
return Mono.just("LLamada a "+urlServer+urlFinal+" Error 4xx: "+x.statusCode()+"\n");
return x.bodyToMono(String.class);
});    
return respuesta1;
}

To insert the body of the message, the auxiliary class BodyInserters will be used. If the message were on the object Mono, this code could be used:

BodyInserters.fromPublisher(Mono.just(MONO_OBJECT),String.class);

When performing a flatMap, the output of the ClientResponse object will be captured and a Mono object will be returned with the string to be returned.

The flatMap function will flatten that Mono object and extract the string inside it, and that is why a Mono <String> will be received and not a Mono <Mono <String>>. However, it would happen if we used the function map.

Making the following call:

curl  -s -XPOST http://localhost:8080/client  -H 'Content-Type: application/json' -d'{"aa": "bbd"}'

The following output will be obtained:

the server said: {aa=bbd}
Headers: content-length:12
Headers: aa:bbd
Headers: accept-encoding:gzip
Headers: Content-Type:application/json
Headers: accept:*/*
Headers: user-agent:ReactorNetty/0.9.0.M3
Headers: host:localhost:8081

This output is produced by the function postExamle of the server

@PostMapping("post")
public ResponseEntity<String> postExample(@RequestBody Map<String,String> body,ServerHttpRequest  request) {
String s="the server said: "+body+"\n";
for (Entry<String, List<String>> map : request.getHeaders().entrySet())
{
s+="Headers: "+map.getKey()+ ":"+map.getValue().get(0)+"\n";
}
return ResponseEntity.ok().body(s);
}

Note that when using the WebFlux library that is not fully compatible with javax.servlet, we must receive a ServerHttpRequest object to collect all raw headers. The equivalent in a non-reactive application would be an HttpServletRequest object.

If you execute the sentence:

curl  -s -XPOST http://localhost:8080/client?url=aa  -H 'Content-Type: application/json' -d'{"aa": "bbd"}'

The client will try to call http://localhost:8081/server/aa, which will cause an error, and the following will be received.

http://localhost:8081/server/aa Called. Error 4xx: 404 NOT_FOUND


The original article was written in Spanish. You can read it at http://www.profesor-p.com/webclient.

Hope you enjoyed!

Requests Reactive programming Java (programming language) Spring Framework Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • How To Build Web Service Using Spring Boot 2.x
  • How to Transform Any Type of Java Bean With BULL
  • Using the Chain of Responsibility Design Pattern in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!