OpenFeign 安裝指南
專案相依性設定
Maven 相依性
<!-- Spring Cloud OpenFeign Starter -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- 如果需要負載平衡支援 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
Gradle 相依性
implementation 'org.springframework.cloud:spring-cloud-starter-openfeign'
implementation 'org.springframework.cloud:spring-cloud-starter-loadbalancer'
版本管理
在 pom.xml 中使用 Spring Cloud BOM 管理版本:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2022.0.4</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
基礎設定
啟用 Feign 客戶端
在主應用類別上新增 @EnableFeignClients 註解:
@SpringBootApplication
@EnableFeignClients
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
指定客戶端掃描套件
如果 Feign 客戶端介面不在主應用類別的套件路徑下,需要指定掃描套件:
@SpringBootApplication
@EnableFeignClients(basePackages = "com.example.clients")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
或者顯式列出客戶端:
@SpringBootApplication
@EnableFeignClients(clients = {UserServiceClient.class, OrderServiceClient.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
建立 Feign 客戶端
基本用法
@FeignClient(name = "user-service")
public interface UserService {
@GetMapping("/users/{id}")
User getUser(@PathVariable("id") Long id);
@GetMapping("/users")
List<User> getAllUsers();
@PostMapping("/users")
User createUser(@RequestBody User user);
@PutMapping("/users/{id}")
User updateUser(@PathVariable("id") Long id, @RequestBody User user);
@DeleteMapping("/users/{id}")
void deleteUser(@PathVariable("id") Long id);
}
使用 URL 屬性
如果不需要服務發現,可以直接指定 URL:
@FeignClient(name = "external-api", url = "https://api.example.com")
public interface ExternalApiClient {
@GetMapping("/data")
ApiResponse getData();
}
支援的註解
OpenFeign 支援以下 Spring MVC 註解:
- HTTP 方法註解:
@GetMapping,@PostMapping,@PutMapping,@DeleteMapping,@PatchMapping - 路徑變數:
@PathVariable - 請求參數:
@RequestParam - 請求主體:
@RequestBody - 請求標頭:
@RequestHeader - Cookie:
@CookieValue
複雜參數範例
@FeignClient(name = "order-service")
public interface OrderService {
// 路徑變數 + 請求參數
@GetMapping("/orders/{userId}")
List<Order> getOrdersByUser(
@PathVariable("userId") Long userId,
@RequestParam("status") String status,
@RequestParam(value = "page", defaultValue = "0") int page
);
// 請求主體 + 請求標頭
@PostMapping("/orders")
@Headers("X-API-Version: 2.0")
Order createOrder(
@RequestBody CreateOrderRequest request,
@RequestHeader("Authorization") String token
);
// 查詢參數 Map
@GetMapping("/orders/search")
List<Order> searchOrders(@SpringQueryMap SearchCriteria criteria);
}
使用 Feign 客戶端
在 Service 中注入
@Service
public class OrderProcessingService {
private final UserService userService;
private final OrderService orderService;
public OrderProcessingService(UserService userService, OrderService orderService) {
this.userService = userService;
this.orderService = orderService;
}
public Order processOrder(Long userId, CreateOrderRequest request) {
// 驗證使用者
User user = userService.getUser(userId);
if (user == null) {
throw new UserNotFoundException("User not found: " + userId);
}
// 建立訂單
return orderService.createOrder(request, "Bearer " + generateToken());
}
private String generateToken() {
// 產生認證令牌
return "token";
}
}
在 Controller 中使用
@RestController
@RequestMapping("/api/v1")
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@GetMapping("/orders/{id}")
public ResponseEntity<Order> getOrder(@PathVariable Long id) {
Order order = orderService.getOrder(id);
return ResponseEntity.ok(order);
}
@PostMapping("/orders")
public ResponseEntity<Order> createOrder(@RequestBody CreateOrderRequest request) {
Order order = orderService.createOrder(request);
return ResponseEntity.status(HttpStatus.CREATED).body(order);
}
}
設定屬性
基本設定
在 application.yml 中設定:
spring:
cloud:
openfeign:
client:
config:
default:
connect-timeout: 5000
read-timeout: 5000
logger-level: basic
user-service:
connect-timeout: 3000
read-timeout: 10000
logger-level: full
日誌級別設定
logging:
level:
com.example.clients.UserService: DEBUG
支援的日誌級別:
- NONE: 不記錄日誌(預設)
- BASIC: 只記錄請求方法、URL 和回應狀態碼、執行時間
- HEADERS: 記錄基本資訊以及請求和回應標頭
- FULL: 記錄標頭、主體和中繼資料(請求和回應)
錯誤處理
自訂錯誤解碼器
@Component
public class CustomErrorDecoder implements ErrorDecoder {
private final ErrorDecoder defaultErrorDecoder = new Default();
@Override
public Exception decode(String methodKey, Response response) {
if (response.status() >= 400 && response.status() < 500) {
return new ClientException("Client error: " + response.status());
} else if (response.status() >= 500) {
return new ServerException("Server error: " + response.status());
}
return defaultErrorDecoder.decode(methodKey, response);
}
}
在設定中註冊
@Configuration
public class FeignConfig {
@Bean
public ErrorDecoder errorDecoder() {
return new CustomErrorDecoder();
}
}
測試 Feign 客戶端
單元測試
@ExtendWith(MockitoExtension.class)
class OrderProcessingServiceTest {
@Mock
private UserService userService;
@Mock
private OrderService orderService;
@InjectMocks
private OrderProcessingService orderProcessingService;
@Test
void shouldProcessOrderSuccessfully() {
// Given
Long userId = 1L;
User user = new User(userId, "John Doe");
CreateOrderRequest request = new CreateOrderRequest();
Order expectedOrder = new Order(1L, userId);
when(userService.getUser(userId)).thenReturn(user);
when(orderService.createOrder(any(), anyString())).thenReturn(expectedOrder);
// When
Order result = orderProcessingService.processOrder(userId, request);
// Then
assertThat(result).isEqualTo(expectedOrder);
verify(userService).getUser(userId);
verify(orderService).createOrder(request, anyString());
}
}
整合測試
@SpringBootTest
@AutoConfigureTestDatabase
class FeignIntegrationTest {
@Autowired
private UserService userService;
@Test
void shouldGetUserFromRemoteService() {
// When
User user = userService.getUser(1L);
// Then
assertThat(user).isNotNull();
assertThat(user.getId()).isEqualTo(1L);
}
}
透過以上步驟,您就可以快速上手使用 OpenFeign 來簡化微服務之間的呼叫。接下來的章節將介紹更多進階特性和最佳實務。
