OpenFeign 學習筆記
一、基礎入門
1.1 簡介
-
OpenFeign 是基于聲明式的 REST 客戶端,用于簡化服務間遠程調用。(編程式 REST 客戶端(RestTemplate))
-
通過接口+注解方式定義 HTTP 請求,自動實現服務調用。
注解驅動
? ? 指定遠程地址:@FeignClient
? ? 指定請求方式:@GetMapping、@PostMapping、@DeleteMapping …
? 指定攜帶數據:@RequestHeader、@RequestParam、@RequestBody …
? ? 指定結果返回:響應模型
-
官網:https://docs.spring.io/spring-cloud-openfeign/reference/spring-cloud-openfeign.html#spring-cloud-feign
-
人話總結:OpenFeign是一種替代RestTemplate的工具,專門用來實現不同微服務之間實現遠程調用的業務API,相比RestTemplate功能更強大,操作更簡介。
1.2 引入依賴
<!-- Spring Cloud OpenFeign 核心依賴 -->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
1.3 開啟功能
在主啟動類添加注解:
@EnableFeignClients // 啟用 OpenFeign 客戶端功能
@SpringBootApplication
public class Application { ... }
1.4 遠程調用
-
定義 Feign 客戶端接口:(客戶端:發送請求 服務端:接收請求)
1.1遠程調用 - 業務API
@FeignClient(name = "user-service") // 指定服務名稱
public interface UserClient {@GetMapping("/user/{id}") // 指定請求路徑(發送請求)User getUserById(@PathVariable Long id);
}
? 1.2遠程調用 - 第三方API
tip:如何編寫好OpenFeign聲明式的遠程調用接口?
? 業務API:直接復制對方Controller簽名即可
? 第三方API:根據接口文檔確定請求如何發
? 2.注入使用:
@Autowired
private UserClient userClient;
public User getUser(Long id) {return userClient.getUserById(id); // 直接調用遠程接口
}
1.5面試題:客戶端負載均衡與服務端負載均衡區別?
答:根據負載均衡發生的位置來區分。
負載均衡發生在客戶端就是客戶端負載均衡。
負載均衡發生在服務端就是服務端負載均衡。
二、進階配置
2.1 開啟日志
配置日志級別(application.yml):
logging:level:com.example.client.UserClient: DEBUG # 指定客戶端接口的日志級別
配置日志策略(Java Config):
@Configuration
public class FeignConfig {@BeanLogger.Level feignLoggerLevel() {return Logger.Level.FULL; // FULL/BASIC/HEADERS/NONE}
}
2.2 超時控制(避免服務器宕機)
spring:cloud:openfeign:client:config:default: # 全局配置logger-level: fullconnect-timeout: 1000 # 連接超時(ms)read-timeout: 2000 # 讀取超時(ms)user-service: # 指定服務的配置logger-level: fullconnect-timeout: 3000read-timeout: 5000
2.3 重試機制
遠程調用超時失敗后,還可以進行多次嘗試,如果某次成功返回ok,如 果多次依然失敗則結束調用,返回錯誤。
spring:cloud:openfeign:client:config:default:retryable: true # 啟用重試maxAttempts: 3 # 最大重試次數
或
@Bean
Retryer retryer(){return new Retryer.Default();
}
2.4 Fallback 兜底返回
1.引入 sentinel
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId></dependency>
2.開啟熔斷
feign:sentinel:enabled: true
3.編寫 fallback 函數
@FeignClient(value = "service-product",fallback = ProductFeignClientFallback.class) // feign客戶端
public interface ProductFeignClient {//mvc注解的兩套使用邏輯//1、標注在Controller上,是接收這樣的請求//2、標注在FeignClient上,是發送這樣的請求@GetMapping("/product/{id}")Product getProductById(@PathVariable("id") Long id);
}
@Component
public class ProductFeignClientFallback implements ProductFeignClient {@Overridepublic Product getProductById(Long id) {System.out.println("兜底回調....");Product product = new Product();product.setId(id);product.setPrice(new BigDecimal("0"));product.setProductName("未知商品");product.setNum(0);return product;}
}
三、攔截器用法
1.請求攔截器
2.響應攔截器(用的不多)
自定義請求攔截器:
import feign.RequestInterceptor;@Component//如果放入IOC容器就會自動注冊攔截器,可以不做后面的注冊
public class XTokenRequestInterceptor implements RequestInterceptor {/***請求攔截器*template 請求模板*/@Overridepublic void apply(RequestTemplate template) {System.out.println("XTokenRequestInterceptor.......");template.header("X-Token", "UUID.randomUUID.toString()"); // 添加請求頭,用作身份驗證}
}
注冊攔截器(配置類中):
@Configuration
public class FeignConfig {@Beanpublic AuthInterceptor authInterceptor() {return new AuthInterceptor();}
}
四、重點總結
核心內容 | 關鍵點 |
---|---|
遠程調用客戶端 | 通過 @FeignClient 定義接口,使用 @GetMapping 等注解聲明 HTTP 方法。 |
超時控制 | 配置 connectTimeout 和 readTimeout ,支持全局和按服務配置。 |
重試機制 | 啟用 retryable 并設置 maxAttempts ,增強服務調用容錯性。 |
Fallback 兜底 | 實現 Fallback 類處理服務降級,防止級聯故障。 |
攔截器 | 通過 RequestInterceptor 添加統一請求頭或認證信息。 |
注意事項:
- 生產環境建議配置合理的超時時間和重試策略,避免雪崩效應。
- 攔截器可用于統一認證、日志跟蹤等場景。