跳到主要内容

OpenFeign 速查表

本文档汇总 OpenFeign 的常用配置、注解和最佳实践,方便快速查阅。

Maven 依赖

<properties>
<spring-cloud.version>2024.0.0</spring-cloud.version>
</properties>

<dependencies>
<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>
</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

启用注解

@SpringBootApplication
@EnableFeignClients(basePackages = "com.example.clients")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

@FeignClient 注解属性

属性说明示例
name / value客户端名称(必填)"user-service"
url直接指定的服务地址"http://localhost:8080"
configuration自定义配置类UserConfig.class
fallback降级处理类UserFallback.class
fallbackFactory降级工厂类UserFallbackFactory.class
path统一路径前缀"/api/v1"
primary是否为首选 Beantrue(默认)
contextId上下文 ID(避免冲突)"userClient"

常用注解

请求映射

@GetMapping("/users")           // GET 请求
@PostMapping("/users") // POST 请求
@PutMapping("/users/{id}") // PUT 请求
@DeleteMapping("/users/{id}") // DELETE 请求
@RequestMapping(method = RequestMethod.GET, value = "/users")

参数绑定

@PathVariable("id") Long id                    // 路径变量
@RequestParam("name") String name // 查询参数
@RequestBody User user // 请求体
@RequestHeader("Authorization") String token // 请求头
@SpringQueryMap UserQuery query // POJO 转查询参数
@RequestPart("file") MultipartFile file // 文件上传
@MatrixVariable("color") String color // 矩阵变量

YAML 配置

基础配置

spring:
cloud:
openfeign:
client:
config:
default: # 全局默认配置
connectTimeout: 5000 # 连接超时(毫秒)
readTimeout: 10000 # 读取超时(毫秒)
loggerLevel: basic # 日志级别
user-service: # 特定客户端配置
connectTimeout: 3000
readTimeout: 5000
decode-slash: false # 是否解码斜杠
remove-trailing-slash: false # 是否移除尾部斜杠
refresh-enabled: false # 启用配置刷新

HTTP 客户端配置

spring:
cloud:
openfeign:
# Java 11 HTTP/2 客户端
http2client:
enabled: true
httpclient:
http2:
version: HTTP_2

# Apache HttpClient 5
httpclient:
hc5:
enabled: true
max-connections: 200
max-connections-per-route: 50
connection-timeout: 5000
socket-timeout: 10000
connection-request-timeout: 3000
pool-concurrency-policy: strict
pool-reuse-policy: fifo

# 通用配置
httpclient:
connection-timeout: 5000
max-connections: 200
max-connections-per-route: 50
time-to-live: 900
follow-redirects: true

# OkHttp
okhttp:
enabled: true

熔断配置

spring:
cloud:
openfeign:
circuitbreaker:
enabled: true
group:
enabled: true # 启用分组熔断器
alphanumeric-ids:
enabled: true # 使用字母数字 ID

压缩配置

spring:
cloud:
openfeign:
compression:
request:
enabled: true
mime-types: text/xml,application/xml,application/json
min-request-size: 2048
content-encoding-types: gzip,deflate
response:
enabled: true

OAuth2 配置

spring:
cloud:
openfeign:
oauth2:
enabled: true
clientRegistrationId: my-client # OAuth2 客户端注册 ID
# 或使用 client-registration-id(负载均衡场景)
client-registration-id: my-client

监控配置

spring:
cloud:
openfeign:
micrometer:
enabled: true

缓存配置

spring:
cloud:
openfeign:
cache:
enabled: true # 默认 true(需要 @EnableCaching)

编码器配置

spring:
cloud:
openfeign:
encoder:
charset-from-content-type: true # 从 Content-Type 获取字符集
lazy-attributes-resolution: true # 懒加载属性解析

自动配置

spring:
cloud:
openfeign:
autoconfiguration:
jackson:
enabled: true # 启用 Page 和 Sort 的 Jackson 模块

默认配置优先级

spring:
cloud:
openfeign:
client:
default-to-properties: true # YAML 配置优先于 Java 配置
default-config: default # 默认配置名称

日志级别

级别说明
NONE不记录日志(默认)
BASIC请求方法、URL、响应状态码、执行时间
HEADERSBASIC + 请求和响应头
FULLHEADERS + 请求和响应体
logging:
level:
com.example.clients.UserClient: DEBUG

核心配置属性速查

HTTP 客户端配置

属性默认值说明
spring.cloud.openfeign.http2client.enabledfalse启用 Java 11 HTTP/2 客户端
spring.cloud.openfeign.httpclient.hc5.enabledfalse启用 Apache HttpClient 5
spring.cloud.openfeign.okhttp.enabledfalse启用 OkHttp
spring.cloud.openfeign.httpclient.max-connections200最大连接数
spring.cloud.openfeign.httpclient.max-connections-per-route50每路由最大连接数
spring.cloud.openfeign.httpclient.connection-timeout10000连接超时(毫秒)

熔断器配置

属性默认值说明
spring.cloud.openfeign.circuitbreaker.enabledfalse启用熔断器
spring.cloud.openfeign.circuitbreaker.group.enabledfalse启用分组熔断器
spring.cloud.openfeign.circuitbreaker.alphanumeric-ids.enabledfalse使用字母数字 ID

客户端配置

属性默认值说明
spring.cloud.openfeign.client.decode-slashfalse是否解码斜杠
spring.cloud.openfeign.client.remove-trailing-slashfalse是否移除 URL 尾部斜杠
spring.cloud.openfeign.client.refresh-enabledfalse启用配置刷新
spring.cloud.openfeign.lazy-attributes-resolutionfalse懒加载属性解析

压缩配置

属性默认值说明
spring.cloud.openfeign.compression.request.enabledfalse启用请求压缩
spring.cloud.openfeign.compression.response.enabledfalse启用响应压缩
spring.cloud.openfeign.compression.request.min-request-size2048最小压缩大小

监控配置

属性默认值说明
spring.cloud.openfeign.micrometer.enabledfalse启用 Micrometer 监控
spring.cloud.openfeign.autoconfiguration.jackson.enabledtrue启用 Page/Sort Jackson 模块
spring.cloud.openfeign.cache.enabledtrue启用缓存能力(需 @EnableCaching

OAuth2 配置

属性默认值说明
spring.cloud.openfeign.oauth2.enabledfalse启用 OAuth2 支持
spring.cloud.openfeign.oauth2.clientRegistrationId-OAuth2 客户端注册 ID
spring.cloud.openfeign.oauth2.client-registration-id-负载均衡场景的客户端 ID

其他配置

属性默认值说明
spring.cloud.openfeign.client.default-to-propertiestrueYAML 配置优先于 Java 配置
spring.cloud.openfeign.client.default-configdefault默认配置名称
spring.cloud.openfeign.encoder.charset-from-content-typefalse从 Content-Type 获取字符集

Java 配置类

public class FeignConfig {

@Bean
public Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}

@Bean
public Request.Options requestOptions() {
return new Request.Options(5000, 10000);
}

@Bean
public Retryer retryer() {
return new Retryer.Default(100, 1000, 3);
}

@Bean
public RequestInterceptor authInterceptor() {
return template -> {
template.header("Authorization", "Bearer token");
};
}

@Bean
public ErrorDecoder errorDecoder() {
return new CustomErrorDecoder();
}
}

拦截器示例

认证拦截器

public class AuthInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
template.header("Authorization", "Bearer " + getToken());
}
}

请求 ID 拦截器

public class RequestIdInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
template.header("X-Request-Id", UUID.randomUUID().toString());
}
}

日志拦截器

public class LoggingInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
log.info("Request: {} {}", template.method(), template.url());
}
}

降级实现

Fallback

@FeignClient(name = "user-service", fallback = UserFallback.class)
public interface UserClient {
@GetMapping("/users/{id}")
User getUserById(@PathVariable("id") Long id);
}

@Component
public class UserFallback implements UserClient {
@Override
public User getUserById(Long id) {
return new User(id, "默认用户", null);
}
}

FallbackFactory

@FeignClient(name = "user-service", fallbackFactory = UserFallbackFactory.class)
public interface UserClient {
@GetMapping("/users/{id}")
User getUserById(@PathVariable("id") Long id);
}

@Component
public class UserFallbackFactory implements FallbackFactory<UserClient> {
@Override
public UserClient create(Throwable cause) {
return id -> {
log.error("Fallback triggered", cause);
return new User(id, "默认用户", null);
};
}
}

文件操作

上传文件

@FeignClient(name = "file-service")
public interface FileClient {
@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
FileResponse upload(@RequestPart("file") MultipartFile file);
}

下载文件

@FeignClient(name = "file-service")
public interface FileClient {
@GetMapping("/download/{id}")
ResponseEntity<byte[]> download(@PathVariable("id") Long id);
}

手动构建客户端

UserClient client = Feign.builder()
.client(client)
.encoder(encoder)
.decoder(decoder)
.contract(contract)
.requestInterceptor(authInterceptor)
.logLevel(Logger.Level.FULL)
.target(UserClient.class, "http://user-service");

常见异常

异常说明处理方式
FeignException.BadRequest400 错误检查请求参数
FeignException.Unauthorized401 错误检查认证信息
FeignException.NotFound404 错误检查请求路径
FeignException.TooManyRequests429 错误实现限流或重试
FeignException.InternalServerError500 错误检查服务端日志
RetryableException可重试异常配置重试策略

最佳实践清单

  • 合理设置超时时间(连接超时 3-5 秒,读取超时根据业务设置)
  • 为非核心功能配置降级策略
  • 使用 FallbackFactory 获取异常信息
  • 配置日志级别便于问题排查
  • 使用拦截器统一处理认证和日志
  • 避免在降级逻辑中调用其他远程服务
  • 监控熔断器状态和指标
  • 区分核心和非核心功能的降级策略

版本兼容

Spring CloudSpring BootOpenFeign
2024.0.x3.4.x4.x
2023.0.x3.2.x, 3.3.x4.x
2022.0.x3.0.x, 3.1.x4.x
2021.0.x2.6.x, 2.7.x3.x

参考链接