What is OpenFeign?
OpenFeign is a declarative HTTP client developed by Netflix and later integrated into the Spring Cloud ecosystem. It simplifies the process of calling remote HTTP APIs by letting developers create Java interfaces and annotate them, eliminating boilerplate code.
Key Features:
Calling REST Services in Spring Boot with Feign
1. Add Feign dependency:
If using Spring Cloud Starter:
groovy
dependencies {
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
}
2. Enable Feign Clients in your Spring Boot application:
java
@SpringBootApplication
@EnableFeignClients
public class MyApplication { ... }
3. Create a Feign Client Interface:
java
@FeignClient(name = "user-service", url = "<http://localhost:8081>")
public interface UserClient {
@GetMapping("/users/{id}")
User getUserById(@PathVariable("id") Long id);
}
4. Use the Feign Client in your service:
java
@Service
public class MyService {
private final UserClient userClient;
public MyService(UserClient userClient) {
this.userClient = userClient;
}
public User getUser(Long id) {
return userClient.getUserById(id);
}
}