What is Spring Cloud OpenFeign?
Spring Cloud OpenFeign is a declarative REST client that integrates seamlessly with Spring Boot, making it easy to create REST clients that communicate with other microservices. By using annotations, you define how to interact with external services without writing any boilerplate code, significantly reducing the effort needed to manage API calls.
Key Features of OpenFeign:
- Declarative REST Clients: No need to manually build HTTP requests. OpenFeign provides annotations to configure endpoints.
- Automatic Load Balancing: Integrates with Netflix Ribbon or Spring Cloud LoadBalancer for distributed systems.
- Integration with Circuit Breakers: OpenFeign integrates with tools like Hystrix and Resilience4j for fault tolerance.
- Pluggable HTTP Clients: Supports different HTTP clients like Apache HttpClient, OKHttp, etc.
Let's have two micro-services: We have used the 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 Spring Cloud OpenFeign 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: Feign]
- Enable Feign Client using @EnableFeignClient in the main class of Employee-Service.
- Create Feign API client service.
- Retrieve Employee information including deptCode from Employee Database.
- Get Department info from Department-Service by deptCode using the Feign Client API.
1. Add Maven Dependency in POM of Employee-Service: To add any Spring Cloud dependency, you need to include three key elements in the POM file. Once the dependencyManagement and its corresponding properties are set for a Spring Cloud dependency, you won’t need to re-add them for subsequent Spring Cloud dependencies.
- Dependency
- Dependency Manager
- Properties file
Dependency & DependencyManagement |
2. Enable Feign Client using @EnableFeignClient annotation in the main class of Employee-Service.
3. Create Feign API client service.
4. Retrieve Employee information including deptCode from Employee Database. And
5. Get Department info from Department-Service by deptCode using the Feign Client API.
DTO : EmployeeResponseDto
Final output in postman
0 Comments