各位在微服務世界摸爬滾打的道友們!今天要解鎖的是Spring Cloud的絕世神通——Feign!這貨堪稱HTTP界的"言出法隨",只需定義接口,就能自動生成HTTP請求代碼!從此告別手動拼裝URL的苦日子,讓你的代碼優雅如詩! ?
一、筑基篇:初識Feign
1.1 法寶祭煉(添加依賴)
<!-- Spring Cloud OpenFeign -->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId><version>4.0.4</version> <!-- 2023最新版本 -->
</dependency>
1.2 開啟Feign法陣
@SpringBootApplication
@EnableFeignClients // 激活Feign魔法
public class MyApp {public static void main(String[] args) {SpringApplication.run(MyApp.class, args);}
}
二、金丹篇:基礎請求術
2.1 定義Feign接口(言出法隨)
@FeignClient(name = "user-service", url = "https://api.example.com")
public interface UserClient {@GetMapping("/users/{id}")User getUserById(@PathVariable("id") Long id);@PostMapping("/users")User createUser(@RequestBody User user);
}
2.2 注入使用(召喚術)
@RestController
public class UserController {@Autowiredprivate UserClient userClient; // Spring會自動實現接口!@GetMapping("/proxy-user/{id}")public User getProxyUser(@PathVariable Long id) {return userClient.getUserById(id); // 直接調用!}
}
三、元嬰篇:高級神通
3.1 自定義配置(個性化法寶)
@FeignClient(name = "order-service", url = "https://api.example.com",configuration = OrderClientConfig.class)
public interface OrderClient {// ...
}// 配置類示例
public class OrderClientConfig {@Beanpublic Logger.Level feignLoggerLevel() {return Logger.Level.FULL; // 開啟詳細日志}@Beanpublic Retryer feignRetryer() {return new Retryer.Default(1000, 2000, 3); // 自定義重試策略}
}
3.2 攔截器(請求煉金術)
public class AuthInterceptor implements RequestInterceptor {@Overridepublic void apply(RequestTemplate template) {template.header("Authorization", "Bearer " + getToken());}private String getToken() {// 獲取JWT令牌的邏輯}
}// 注冊攔截器
@Bean
public AuthInterceptor authInterceptor() {return new AuthInterceptor();
}
四、化神篇:異常處理
4.1 自定義錯誤解碼器(渡劫護盾)
public class CustomErrorDecoder implements ErrorDecoder {@Overridepublic Exception decode(String methodKey, Response response) {if (response.status() == 404) {return new NotFoundException("資源不存在");}return new RuntimeException("請求失敗: " + response.status());}
}// 注冊解碼器
@Bean
public ErrorDecoder errorDecoder() {return new CustomErrorDecoder();
}
4.2 Fallback處理(降級大法)
@FeignClient(name = "product-service", fallback = ProductClientFallback.class)
public interface ProductClient {@GetMapping("/products/{id}")Product getProduct(@PathVariable Long id);
}// 降級實現
@Component
public class ProductClientFallback implements ProductClient {@Overridepublic Product getProduct(Long id) {return new Product(0L, "默認商品", 0.0); // 返回兜底數據}
}
五、大乘篇:性能調優
5.1 啟用GZIP壓縮(縮地成寸)
# application.yml
feign:compression:request:enabled: truemime-types: text/xml,application/xml,application/jsonmin-request-size: 2048response:enabled: true
5.2 連接池配置(靈氣循環)
feign:httpclient:enabled: truemax-connections: 500max-connections-per-route: 50
六、實戰心法
6.1 文件上傳(乾坤大挪移)
@FeignClient(name = "file-service")
public interface FileClient {@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)String uploadFile(@RequestPart("file") MultipartFile file);
}
6.2 與Eureka集成(服務發現)
# application.yml
eureka:client:serviceUrl:defaultZone: http://localhost:8761/eureka/feign:client:config:default:connectTimeout: 5000readTimeout: 30000
@FeignClient(name = "user-service") // 直接使用服務名
public interface UserClient {// ...
}
飛升指南:最佳實踐
- 接口設計:保持Feign接口與提供方API一致
- 版本控制:建議使用
@RequestMapping
指定API版本 - 日志監控:配置
Logger.Level.FULL
方便調試 - 超時設置:生產環境必須配置合理超時