Appearance
OpenFeign简介
OpenFeign是由Spring Cloud社区在原生Feign基础上二次开发和完善的产物。在原生基础上,增加了与负载均衡器、熔断器等组件的自动集成,提供与Spring Boot框架无缝集成的“开箱即用”体验。
OpenFeign的使用
项目依赖配置
xml
<!-- Spring Cloud OpenFeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 可选:集成熔断器 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
<!-- 可选:HTTP客户端(替代默认JDK HttpURLConnection) -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-okhttp</artifactId>
</dependency>主启动类加@EnableFeignClients注解
java
@SpringBootApplication
@EnableFeignClients // 启用OpenFeign
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}定义Feign接口
java
// 定义Feign接口
@FeignClient(name = "user-service")
public interface UserService {
@GetMapping("/users/{id}")
User getUserById(@PathVariable("id") Long id);
}相关配置
- 超时时间设置,建议: 连接超时通常设置为 2-5 秒。 读取超时根据接口业务复杂度设置,简单查询一般 5-10 秒,复杂业务一般 30-60 秒,支付/文件处理一般 60 秒以上。
- HTTP客户端选择:OkHttp(性能更好,推荐生产环境使用);Apache HttpClient(功能丰富,稳定性好);默认JDK HttpClient(无需额外依赖,性能一般)。
- 日志级别: NONE(默认的,不显示任何日志);BASIC(仅记录请求方法、URL、响应状态码及执行时间);HEADERS(除了 BASIC 中定义的信息之外,还有请求和响应的头信息);FULL(除了 HEADERS 中定义的信息之外,还有请求和响应的正文及元数据)。
部分样例:
yaml
# OpenFeign配置
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 30000
loggerLevel: basic
okhttp:
enabled: true # 启用OkHttp作为底层客户端(性能更好)
compression:
request:
enabled: true
mime-types: text/xml,application/xml,application/json
response:
enabled: true
# HTTP连接池配置(使用OkHttp时)
okhttp:
max-idle-connections: 200
keep-alive-duration: 300000