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简化服务调用的协作过程,是构建微服务架构的基础设施。