1. What is WebClient?
WebClient is part of the Spring WebFlux module and is designed for asynchronous, non-blocking HTTP requests. It is a modern replacement for the older RestTemplate and offers a more flexible and functional approach to making HTTP calls. With WebClient, you can easily perform GET, POST, PUT, DELETE, and other HTTP operations with minimal boilerplate code.
Key Features of WebClient
- Non-Blocking
- Fluent API
- Error Handling
- Support for Reactive Streams
When to use WebClient:
- When you want to leverage non-blocking I/O for performance.
- In reactive microservice architectures.
- For enhanced flexibility and error handling over RestTemplate.
Let's have two micro-services: We have used Spring Boot 3.3 version.
- Employee-Service
- Department-Service
1. Employee Entity & Employee Rest API
Employee Entity
2. Departments Entity & Department Rest API
Requirements:
Call an HTTP request from Postman to get specific Employee information from Employee-Service and get respective Departmental information from Department-Service of that employee.
Here Employee-Service will communicate with Department-Service using WebClient to fetch the Departmental info of an Employee. Then return the complete information to Postman.
Development Steps:
- Add Maven Dependency in Employee-Service's POM. [ Dependency : spring-boot-starter-webflux]
- Create a WebClient @Bean in the main class of Employee-Service.
- Inject the WebClient in ServiceImpl class.
- Retrieve Employee information including deptCode from Employee Database.
- Make an HTTP request to Department-Service to get Departmental information by deptCode using the WebClient object.
1. Add Maven Dependency in POM of Employee-Service:
2. Create a @Bean of WebClient in the Employee-Service's main class.
3. Inject the WebClient object in the ServiceImpl class of Employee-Service.
4. Retrieve Employee information including deptCode in Employee-Service.
5. Make an HTTP request to Department-Service to get Departmental information by deptCode using the WebClient.
DTO : EmployeeResponseDto
Final output in postman
0 Comments