Eureka 與 Feign 知識解析
1. Eureka
Spring Cloud Eureka 是服務發現組件,包含:
- Eureka Server:注冊中心,管理服務實例
- Eureka Client:服務實例,向注冊中心注冊/獲取服務信息
核心功能:
- 服務注冊與發現
- 心跳檢測(默認30秒)
- 服務故障自動剔除
- 客戶端緩存注冊信息
2. OpenFeign
聲明式 HTTP 客戶端工具,核心特性:
- 基于接口的聲明式調用
- 整合 Ribbon 實現負載均衡
- 整合 Hystrix 實現熔斷(需額外配置)
- 自動處理 HTTP 請求/響應序列化
依賴關系
<!-- Eureka Server -->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency><!-- Eureka Client + OpenFeign -->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
完整示例代碼
1. Eureka Server (服務注冊中心)
application.yml
server:port: 8761
eureka:client:register-with-eureka: falsefetch-registry: false
EurekaServerApplication.java
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {public static void main(String[] args) {SpringApplication.run(EurekaServerApplication.class, args);}
}
2. Service Provider (服務提供者)
application.yml
server:port: 8081
spring:application:name: user-service
eureka:client:service-url:defaultZone: http://localhost:8761/eureka/
UserController.java
@RestController
@RequestMapping("/users")
public class UserController {@GetMapping("/{id}")public User getUser(@PathVariable Long id) {return new User(id, "用戶" + id, "user" + id + "@example.com");}
}// 實體類
public class User {private Long id;private String name;private String email;// 構造方法/getters/setters
}
3. Service Consumer (服務消費者)
application.yml
server:port: 8080
spring:application:name: order-service
eureka:client:service-url:defaultZone: http://localhost:8761/eureka/
Feign Client 接口
@FeignClient(name = "user-service")
public interface UserServiceClient {@GetMapping("/users/{id}")User getUserById(@PathVariable("id") Long userId);// 請求參數示例@GetMapping("/users/search")User searchUser(@RequestParam("name") String name);
}
OrderController.java
@RestController
@RequestMapping("/orders")
public class OrderController {@Autowiredprivate UserServiceClient userServiceClient;@GetMapping("/{orderId}/user")public User getOrderUser(@PathVariable Long orderId) {// 通過Feign調用用戶服務Long userId = orderId * 10; // 模擬用戶IDreturn userServiceClient.getUserById(userId);}
}
啟用Feign (主類)
@SpringBootApplication
@EnableFeignClients
public class OrderServiceApplication {public static void main(String[] args) {SpringApplication.run(OrderServiceApplication.class, args);}
}
4. 高級配置
自定義Feign配置
@Configuration
public class FeignConfig {@BeanLogger.Level feignLoggerLevel() {return Logger.Level.FULL; // 詳細日志}@Beanpublic RequestInterceptor authInterceptor() {return template -> template.header("Authorization", "Bearer token123");}
}
使用配置
@FeignClient(name = "user-service",configuration = FeignConfig.class,fallback = UserServiceFallback.class // 熔斷回退
)
public interface UserServiceClient { ... }
熔斷回退實現
@Component
public class UserServiceFallback implements UserServiceClient {@Overridepublic User getUserById(Long userId) {return new User(0L, "備用用戶", "fallback@example.com");}
}
日志配置 (application.yml)
logging:level:org.springframework.cloud.openfeign: DEBUG
測試流程
- 啟動 Eureka Server (8761端口)
- 啟動 User Service (8081端口)
- 啟動 Order Service (8080端口)
- 訪問測試:
http://localhost:8080/orders/123/user
關鍵概念總結
- 服務注冊:Provider 啟動時向 Eureka 注冊信息
- 服務發現:Consumer 通過服務名發現 Provider
- 負載均衡:Feign 自動實現多實例輪詢
- 聲明式調用:定義接口即完成遠程調用
- 熔斷機制:快速失敗 + 服務降級
注:當前 Spring Cloud 版本默認使用 LoadBalancer 替代 Ribbon,最新版 OpenFeign 已內置負載均衡能力。
通過這個完整示例,可以清晰看到Eureka實現服務治理、Feign簡化服務調用的協作過程,是構建微服務架構的基礎設施。