OpenFeign 使用手冊
負載平衡
Spring Cloud LoadBalancer 整合
OpenFeign 預設整合了 Spring Cloud LoadBalancer,提供客戶端負載平衡功能。
@FeignClient(name = "user-service")
public interface UserService {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") Long id);
}
在 application.yml 中設定服務實例:
spring:
cloud:
discovery:
client:
simple:
instances:
user-service:
- uri: http://localhost:8081
- uri: http://localhost:8082
- uri: http://localhost:8083
自訂負載平衡策略
@Configuration
public class LoadBalancerConfig {
@Bean
public ServiceInstanceListSupplier serviceInstanceListSupplier(
ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder()
.withDiscoveryClient()
.withCaching()
.build(context);
}
}
轉換負載平衡 HTTP 請求
@Bean
public LoadBalancerFeignRequestTransformer transformer() {
return new LoadBalancerFeignRequestTransformer() {
@Override
public Request transformRequest(Request request, ServiceInstance instance) {
Map<String, Collection<String>> headers = new HashMap<>(request.headers());
headers.put("X-ServiceId", Collections.singletonList(instance.getServiceId()));
headers.put("X-InstanceId", Collections.singletonList(instance.getInstanceId()));
return Request.create(request.httpMethod(), request.url(), headers,
request.body(), request.charset(), request.requestTemplate());
}
};
}
熔斷器支援
Spring Cloud CircuitBreaker 整合
啟用熔斷器支援:
spring:
cloud:
openfeign:
circuitbreaker:
enabled: true
熔斷器回退
@FeignClient(name = "user-service", fallback = UserServiceFallback.class)
public interface UserService {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") Long id);
}
@Component
public class UserServiceFallback implements UserService {
@Override
public User getUser(Long id) {
// 傳回預設使用者或拋出特定例外
return new User(id, "Default User");
}
}
帶例外資訊的回退工廠
@FeignClient(name = "user-service", fallbackFactory = UserServiceFallbackFactory.class)
public interface UserService {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") Long id);
}
@Component
public class UserServiceFallbackFactory implements FallbackFactory<UserService> {
@Override
public UserService create(Throwable cause) {
return new UserService() {
@Override
public User getUser(Long id) {
// 可以存取導致回退的例外原因
log.error("UserService fallback triggered", cause);
return new User(id, "Fallback User");
}
};
}
}
自訂熔斷器名稱
@Configuration
public class CircuitBreakerConfig {
@Bean
public CircuitBreakerNameResolver circuitBreakerNameResolver() {
return (String feignClientName, Target<?> target, Method method) ->
feignClientName + "_" + method.getName();
}
}
日誌記錄
設定日誌級別
@Configuration
public class FeignLoggingConfig {
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
}
或者透過設定檔:
logging:
level:
com.example.clients.UserService: DEBUG
spring:
cloud:
openfeign:
client:
config:
user-service:
logger-level: full
自訂日誌過濾
public class CustomLogger extends Logger {
@Override
protected void logRequest(String configKey, Level logLevel, Request request) {
// 過濾敏感資訊
if (!shouldLogRequestHeader(request)) {
// 自訂日誌邏輯
}
}
@Override
protected Response logAndRebufferResponse(String configKey, Level logLevel,
Response response, long elapsedTime) throws IOException {
// 過濾敏感回應資訊
if (!shouldLogResponseHeader(response)) {
// 自訂日誌邏輯
}
return super.logAndRebufferResponse(configKey, logLevel, response, elapsedTime);
}
private boolean shouldLogRequestHeader(Request request) {
// 過濾 Authorization 標頭等敏感資訊
return !request.headers().containsKey("Authorization");
}
private boolean shouldLogResponseHeader(Response response) {
return true; // 或者根據需要過濾
}
}
請求/回應壓縮
啟用壓縮
spring:
cloud:
openfeign:
compression:
request:
enabled: true
mime-types: text/xml,application/xml,application/json
min-request-size: 2048
response:
enabled: true
注意事項
- 當使用 OkHttpClient 時,如果存在
content-encoding或accept-encoding標頭,壓縮會被停用 - 壓縮僅對指定的 MIME 類型生效
- 請求大小必須超過
min-request-size才會進行壓縮
OAuth2 支援
啟用 OAuth2
spring:
cloud:
openfeign:
oauth2:
enabled: true
client-registration-id: my-client
相依性設定
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
OAuth2 客戶端設定
spring:
security:
oauth2:
client:
registration:
my-client:
client-id: your-client-id
client-secret: your-client-secret
authorization-grant-type: client_credentials
scope: read,write
provider:
my-provider:
token-uri: https://auth-server.com/oauth/token
快取支援
啟用快取
@SpringBootApplication
@EnableCaching
@EnableFeignClients
public class Application {
// ...
}
在 Feign 客戶端中使用快取
@FeignClient(name = "data-service")
public interface DataService {
@GetMapping("/data/{key}")
@Cacheable(cacheNames = "data-cache", key = "#key")
Data getData(@PathVariable String key);
@PostMapping("/data")
@CachePut(cacheNames = "data-cache", key = "#data.key")
Data updateData(@RequestBody Data data);
@DeleteMapping("/data/{key}")
@CacheEvict(cacheNames = "data-cache", key = "#key")
void deleteData(@PathVariable String key);
}
停用快取
spring:
cloud:
openfeign:
cache:
enabled: false
非同步支援
CompletableFuture 支援
@FeignClient(name = "async-service")
public interface AsyncService {
@GetMapping("/data/{id}")
CompletableFuture<Data> getDataAsync(@PathVariable String id);
}
設定非同步客戶端
@Configuration
public class AsyncFeignConfig {
@Bean
public AsyncClient asyncClient() {
return new AsyncClient.Default();
}
}
使用範例
@Service
public class AsyncProcessingService {
private final AsyncService asyncService;
public AsyncProcessingService(AsyncService asyncService) {
this.asyncService = asyncService;
}
public void processData() {
CompletableFuture<Data> future1 = asyncService.getDataAsync("1");
CompletableFuture<Data> future2 = asyncService.getDataAsync("2");
// 平行處理
CompletableFuture.allOf(future1, future2).thenRun(() -> {
try {
Data data1 = future1.get();
Data data2 = future2.get();
// 處理資料
} catch (Exception e) {
log.error("Error processing async data", e);
}
});
}
}
繼承支援
基礎介面定義
public interface BaseService<T, ID> {
@GetMapping("/{id}")
T findById(@PathVariable ID id);
@GetMapping
List<T> findAll();
@PostMapping
T save(@RequestBody T entity);
@DeleteMapping("/{id}")
void deleteById(@PathVariable ID id);
}
具體服務實作
@FeignClient(name = "user-service")
public interface UserService extends BaseService<User, Long> {
@GetMapping("/users/by-email/{email}")
User findByEmail(@PathVariable String email);
}
@FeignClient(name = "order-service")
public interface OrderService extends BaseService<Order, Long> {
@GetMapping("/orders/by-user/{userId}")
List<Order> findByUserId(@PathVariable Long userId);
}
查詢參數對應
使用 @SpringQueryMap
public class SearchCriteria {
private String name;
private String status;
private Integer page;
private Integer size;
// getters and setters
}
@FeignClient(name = "search-service")
public interface SearchService {
@GetMapping("/search")
SearchResult search(@SpringQueryMap SearchCriteria criteria);
}
自訂 QueryMapEncoder
@Configuration
public class FeignConfig {
@Bean
public QueryMapEncoder queryMapEncoder() {
return new BeanQueryMapEncoder(); // 使用 Java Bean 屬性
// 或者 return new CustomQueryMapEncoder(); // 自訂實作
}
}
HATEOAS 支援
啟用 HATEOAS
新增相依性:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
</dependency>
使用 HATEOAS 模型
@FeignClient(name = "hateoas-service")
public interface HateoasService {
@GetMapping("/resources")
CollectionModel<Resource> getResources();
@GetMapping("/resources/{id}")
EntityModel<Resource> getResource(@PathVariable String id);
}
重新整理作用域支援
啟用重新整理支援
spring:
cloud:
openfeign:
client:
refresh-enabled: true
重新整理設定
透過 Actuator 重新整理端點:
POST /actuator/refresh
注意事項
- 不要在
@FeignClient介面上使用@RefreshScope註解 - 重新整理功能預設是停用的,需要顯式啟用
- 支援重新整理連線逾時、讀取逾時和 URL 設定
AOT 和原生映像支援
設定要求
spring:
cloud:
refresh:
enabled: false
openfeign:
client:
refresh-enabled: false
lazy-attributes-resolution: false
建立原生映像
確保在建置時設定正確的設定,並在執行時可以透過系統屬性覆寫 URL:
-Dspring.cloud.openfeign.client.config.[clientId].url=[url]
這些進階特性使得 OpenFeign 不僅是一個簡單的 HTTP 客戶端,而是一個功能完整的微服務通訊解決方案,能夠滿足企業級應用的各種需求。
