2. Java Spring Boot Micro-service Communication using WebClient

 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.

Architecture of WebClient Communication



Key Features of WebClient
  1. Non-Blocking
  2. Fluent API
  3. Error Handling
  4. Support for Reactive Streams

When to use WebClient:
  1. When you want to leverage non-blocking I/O for performance.
  2. In reactive microservice architectures.
  3. For enhanced flexibility and error handling over RestTemplate.

Let's have two micro-services: We have used Spring Boot 3.3 version.
  1. Employee-Service
  2. Department-Service
1. Employee Entity & Employee Rest API 

Employee Entity
Employee Entity

Employee Rest Controller
Employee Controller

2. Departments Entity & Department Rest API 

Department Entity
Department Entity

Department Rest Controller
Department Controller


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:
  1. Add Maven Dependency in Employee-Service's POM. [ Dependency : spring-boot-starter-webflux]
  2. Create a WebClient @Bean in the main class of Employee-Service.
  3. Inject the WebClient in ServiceImpl class.
  4. Retrieve Employee information including deptCode from Employee Database.
  5. 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:
Added Maven dependency (WebFlux)


2. Create a @Bean of WebClient in the Employee-Service's main class.

Created Bean in 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.

Inject bean in ServiceImpl class

DTO : EmployeeResponseDto
Final Dto to response both Employee & Department info


Final output in postman
Output in Postman

Done 😃



Post a Comment

0 Comments