OpenFeign 声明式调用
约 490 字大约 2 分钟
布欧-Lewyon
2026-05-15
首页 › Spring Cloud › 服务调用
OpenFeign 是声明式 HTTP 客户端,写一个接口即可调用远程服务。
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>启用 Feign
@SpringBootApplication
@EnableFeignClients(basePackages = "com.shop.cloud.feign")
public class OrderServiceApplication {
public static void main(String[] args) {
SpringApplication.run(OrderServiceApplication.class, args);
}
}声明 Feign 接口
package com.shop.cloud.feign;
// 调用 user-service
@FeignClient(name = "user-service", path = "/api/users")
public interface UserFeignClient {
@GetMapping("/{id}")
Result<User> getUser(@PathVariable("id") Long id);
@PostMapping("/batch")
Result<List<User>> getUsers(@RequestBody List<Long> ids);
}
// 调用 product-service
@FeignClient(name = "product-service", path = "/api/products")
public interface ProductFeignClient {
@GetMapping("/{id}")
Result<Product> getProduct(@PathVariable("id") Long id);
@PutMapping("/{id}/stock")
Result<Void> deductStock(@PathVariable("id") Long id,
@RequestParam("quantity") Integer quantity);
}使用 Feign
@Service
public class OrderCreateService {
@Autowired
private UserFeignClient userFeignClient;
@Autowired
private ProductFeignClient productFeignClient;
public Order createOrder(Long userId, Long productId, Integer quantity) {
// 1. 查询用户
User user = userFeignClient.getUser(userId).getData();
// 2. 查询商品
Product product = productFeignClient.getProduct(productId).getData();
// 3. 计算金额
BigDecimal total = product.getPrice().multiply(BigDecimal.valueOf(quantity));
// 4. 创建订单
Order order = new Order(userId, productId, quantity, total);
// 5. 扣减库存
productFeignClient.deductStock(productId, quantity);
return saveOrder(order);
}
}Feign 参数说明
@FeignClient(
name = "user-service", // 目标服务名(从 Nacos 发现)
url = "${user.service.url:}", // 直接指定 URL(调试时用)
path = "/api/users", // 统一前缀
contextId = "user", // Bean 名称(防止多个 Feign Client 冲突)
primary = true // 有多个同类型 Bean 时指定
)统一结果处理
@Data
public class Result<T> {
private Integer code;
private String msg;
private T data;
public boolean isSuccess() {
return code == 200;
}
public static <T> Result<T> success(T data) {
Result<T> r = new Result<>();
r.code = 200;
r.data = data;
return r;
}
}核心注解对应
| Spring MVC | Feign |
|---|---|
@GetMapping | @GetMapping |
@PostMapping | @PostMapping |
@PathVariable | @PathVariable |
@RequestParam | @RequestParam |
@RequestBody | @RequestBody |
@RequestHeader | @RequestHeader |
Feign 的注解与 Spring MVC 相同,学习成本极低。
小结
@FeignClient(name = "user-service")声明远程服务接口。- 注解与 Spring MVC 一致(
@GetMapping/@PostMapping/@PathVariable等)。 @EnableFeignClients启用 Feign,basePackages指定扫描路径。- Feign 内部集成 Ribbon(或 LoadBalancer)做负载均衡。
- 生产建议配合 Sentinel 做 Feign 的容错降级。
上一节:服务发现与调用 下一节:Feign 配置与拦截器
