Spring WebFlux — WebClient

Reading Time: 3 minutes

Overview

This Blog will see how we could use Spring WebFlux WebClient for making non-blocking HTTP requests.

What Is the WebClient?

Just put, the WebClient class which provides a common method for sending or receiving data from any local, intranet, or Internet resource which is identified by a URI. The WebClient class uses the WebRequest class which provides the access to resources. It is an interface that stands for the main entry point for performing web requests.

It was created as part of the Spring Web Reactive module and will be replacing the classic RestTemplate in these frameworks. Similarly, In addition, the new client is a reactive, non-blocking solution that works over the HTTP/1.1 protocol.

It’s very important to note that even though it is, in fact, a non-blocking client and it belongs to the spring-web flux library, the solution offers support for both synchronous and asynchronous operations, which makes it suitable also for applications running on a Servlet Stack.

This can be also achieved by blocking the operation to get the result. Of course, this practice is not recommended if we’re working on a Reactive Stack.

Lastly, the interface has a single execution, the DefaultWebClient class, which we’ll be working with.

WebClient — It is a non-blocking, reactive client to perform HTTP requests, and reveal a fluent, reactive API over underlying HTTP client libraries such as Reactor Netty.
We can use static factory methods create() or create(String), or builder() to build an instance.
For examples with a response body can see below:
– retrieve()
– exchangeToMono()
– exchange flux()

Below are examples with a request body see here:
– bodyValue(Object)
– body(Publisher, Class)

db.json

Start the command using Docker

docker run -d -p 8000:80 -v ${PWD}/db.json:/data/db.json clue/json-server

pom.xml

Post.java

Comment.java

Test class

All endpoints-

// all posts
 
http://localhost:8000/posts 

// all comments 

http://localhost:8000/comments 

// post 1 comments 

http://localhost:8000/posts/1/comments

Reference

Written by 

He is a Software Consultant at Knoldus Inc. He has done B.Tech from Dr. APJ Kalam Technical University Uttar-Pradesh. He is passionate about his work and having the knowledge of various programming languages like Java, C++, Python. But he is passionate about Java development and curious to learn Java Technologies. He is always impatient and enthusiastic to learn new things. He is good skills of Critical thinking and problem solving and always enjoy to help others. He likes to play outdoor games like Football, Volleyball, Hockey and Kabaddi. Apart from the technology he likes to read scriptures originating in ancient India like Veda,Upanishad,Geeta etc.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading