跳到主要内容

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

熔断配置

spring:
cloud:
openfeign:
circuitbreaker:
enabled: true

压缩配置

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

OAuth2 配置

spring:
cloud:
openfeign:
oauth2:
enabled: true
clientRegistrationId: my-client

日志级别

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

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

参考链接