OpenFeign
2026年3月10日大约 2 分钟
OpenFeign
OpenFeign 是一个声明式的 HTTP 客户端,简化了服务之间的通信。它允许开发者通过接口定义来调用远程服务,而不需要编写大量的样板代码。
使用步骤
- 添加依赖:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>- 添加均衡负载依赖(可选):
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> - 启用Feign功能,在主类或者配置类上添加
@EnableFeignClients注解:@EnableFeignClients @SpringBootApplication public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } - 定义Feign客户端接口:
@FeignClient(name = "other-service") // 指定要调用的服务名称 public interface OtherServiceClient { @GetMapping("/api/endpoint") // 指定要调用的接口路径 String callOtherService(); } - 注入Feign客户端并调用:
@Resource private OtherServiceClient otherServiceClient; public void callService() { String response = otherServiceClient.callOtherService(); // 处理响应 }
连接池
OpenFeign默认使用HttpUrlConnection处理远程调用
- HttpUrlConnection:默认实现,不支持连接池。
- Apache HttpClient:支持连接池。
- OkHttp:支持连接池。
连接池配置
下面以OkHttp为例,介绍如何配置连接池:
- 添加OkHttp依赖:
<dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-okhttp</artifactId> </dependency> - 在
application.yml启用连接池:feign: okhttp: enabled: true
最佳实践
- 抽取 Feign 客户端到独立 module
- 以
com.example.feignclient为例,创建一个独立的 module 来存放 Feign 客户端接口,这样可以实现模块化开发,降低耦合度。
- 以
- 在需要调用的模块引入该模块
- 在需要调用远程服务的模块中引入 Feign 客户端所在的 module,例如:
<dependency> <groupId>com.example</groupId> <artifactId>feignclient</artifactId> <version>1.0.0</version> </dependency> - 在调用方启动类上 添加
@EnableFeignClients注解并加上参数, 启用 Feign 扫描- 方式1:声明扫描包:
@EnableFeignClients(basePackages = "com.example.feignclient") - 方式2:声明扫描类:
@EnableFeignClients(clients = OtherServiceClient.class)
@EnableFeignClients(basePackages = "com.example.feignclient") @SpringBootApplication public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } } - 方式1:声明扫描包:
日志配置
Feign 提供了日志功能,可以通过配置日志级别来控制日志输出的详细程度。
- 在 Feign客户端 模块,添加日志配置类:
@Configuration public class FeignConfig { @Bean Logger.Level feignLoggerLevel() { return Logger.Level.FULL; // 配置feign日志级别 } } - 进行配置
- 局部生效: 在 Feign客户端接口上添加
@FeignClient注解时,添加configuration参数,指定配置类:@FeignClient(name = "other-service", configuration = FeignConfig.class) public interface OtherServiceClient { @GetMapping("/api/endpoint") String callOtherService(); } - 全局生效: 在调用方启动类上添加
@EnableFeignClients注解时,添加defaultConfiguration参数,指定默认配置类:@EnableFeignClients(basePackages = "com.example.feignclient", defaultConfiguration = FeignConfig.class) @SpringBootApplication public class YourApplication { public static void main(String[] args) { SpringApplication.run(YourApplication.class, args); } }