OpenFeign 是 Spring Cloud 组件之一,用于在微服务架构中实现 声明式 HTTP 客户端。它让我们可以像调用本地方法一样调用远程 HTTP 接口,简化了 RESTful API 的调用逻辑。
声明式 HTTP 调用:只需定义接口,无需手动拼接 URL。
集成 Ribbon 负载均衡(Spring Cloud 2020 之后默认使用 Spring LoadBalancer)。
支持 Hystrix 熔断机制(Spring Cloud 2020 之后推荐使用 Sentinel)。
支持请求拦截器和日志,方便调试。
在 Spring Boot 项目的 pom.xml
文件中添加 OpenFeign 依赖:
org.springframework.cloud
spring-cloud-starter-openfeign
在 Spring Boot 启动类上添加 @EnableFeignClients
注解:
@SpringBootApplication
@EnableFeignClients
public class OpenFeignApplication {
public static void main(String[] args) {
SpringApplication.run(OpenFeignApplication.class, args);
}
}
创建一个 Feign 客户端接口,模拟调用 user-service
微服务的接口:
@FeignClient(name = "user-service")
public interface UserClient {
@GetMapping("/user/{id}")
User getUserById(@PathVariable("id") Long id);
}
注意事项:
@FeignClient(name = "user-service")
中的 name
必须与 Nacos/Eureka 注册中心的服务名称一致。
@PathVariable
需要 显式指定参数名,否则 Feign 可能无法正确解析参数。
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private UserClient userClient;
@GetMapping("/create")
public String createOrder(@RequestParam Long userId) {
User user = userClient.getUserById(userId);
return "Order created for user: " + user.getName();
}
}
在 application.yml
中配置 Feign 的日志级别:
logging:
level:
feign: DEBUG
在 Feign 客户端上设置日志级别:
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
日志级别解释:
NONE
(默认):不记录日志。
BASIC
:记录请求方法、URL、响应状态等基本信息。
HEADERS
:记录请求和响应头信息。
FULL
:记录所有请求、响应的详细信息。
feign:
client:
config:
default:
connectTimeout: 5000 # 连接超时时间 5s
readTimeout: 10000 # 读取超时时间 10s
Feign 提供拦截器,可用于请求头认证、日志记录等。
@Component
public class FeignRequestInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("Authorization", "Bearer example-token");
}
}
@FeignClient(name = "payment-service")
public interface PaymentClient {
@PostMapping("/payment/process")
String processPayment(@RequestBody PaymentRequest request);
}
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private PaymentClient paymentClient;
@PostMapping("/pay")
public String payOrder(@RequestBody PaymentRequest request) {
return paymentClient.processPayment(request);
}
}
启动 payment-service
,监听 /payment/process
。
启动 order-service
,调用 payment-service
进行支付。
引入依赖:spring-cloud-starter-openfeign
。
启用 Feign:@EnableFeignClients
。
创建 FeignClient 接口:使用 @FeignClient
注解。
使用 Feign 进行远程调用:在 Controller 或 Service 层调用 FeignClient 方法。
配置日志、超时和拦截器:提高可观测性和安全性。
OpenFeign 让微服务间的 HTTP 调用变得更加优雅和简单,是 Spring Cloud 体系中的重要组件。如果你觉得这篇教程对你有帮助,欢迎 点赞、收藏、评论,也可以 关注我,一起交流更多技术内容!