Spring Cloud 技术实战
Spring Cloud 简介
Spring Cloud 是基于 Spring Boot 构建的微服务框架,提供了一套完整的微服务解决方案。它利用 Spring Boot 的开发便利性,并通过各种组件简化分布式系统的开发。
核心组件
- Spring Cloud Netflix Eureka: 服务注册与发现
- Spring Cloud Gateway: API 网关
- Spring Cloud Config: 配置中心
- Spring Cloud OpenFeign: 声明式 REST 客户端
- Spring Cloud Circuit Breaker: 断路器
- Spring Cloud Sleuth & Zipkin: 分布式追踪
实战部署
项目结构
spring-cloud-demo/
├── eureka-server/ # 服务注册中心
├── config-server/ # 配置中心
├── gateway-service/ # API 网关
├── user-service/ # 用户服务
├── order-service/ # 订单服务
└── pom.xml # 父 POM
步骤一:创建父项目
创建 pom.xml
,管理依赖版本:
<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.7</version>
</parent><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>2021.0.2</version><type>pom</type><scope>import</scope></dependency></dependencies>
</dependencyManagement>
步骤二:Eureka 服务注册中心
- 添加依赖:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
- 配置
application.yml
:
server:port: 8761eureka:client:register-with-eureka: falsefetch-registry: false
- 启动类添加
@EnableEurekaServer
注解
步骤三:配置中心
- 添加依赖:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-config-server</artifactId>
</dependency>
- 配置
application.yml
:
server:port: 8888spring:cloud:config:server:git:uri: https://github.com/your-repo/config-repodefault-label: main
- 启动类添加
@EnableConfigServer
注解
步骤四:API 网关
- 添加依赖:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 配置路由:
spring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/api/users/**- id: order-serviceuri: lb://order-servicepredicates:- Path=/api/orders/**
步骤五:微服务实现
- 创建公共模块依赖:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<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>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
- 服务调用示例:
@FeignClient(name = "user-service")
public interface UserClient {@GetMapping("/api/users/{id}")User getUserById(@PathVariable("id") Long id);
}
服务降级策略
在微服务架构中,服务降级是保障系统可用性的关键策略。Spring Cloud 提供了多种服务降级机制,主要通过 Resilience4j(替代了之前的 Hystrix)实现。
1. 断路器(Circuit Breaker)
断路器模式用于防止服务级联故障。当某个服务频繁失败时,断路器会"断开",快速失败而不是等待超时。
添加依赖:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
配置断路器:
resilience4j:circuitbreaker:instances:userService:registerHealthIndicator: trueslidingWindowSize: 10minimumNumberOfCalls: 5permittedNumberOfCallsInHalfOpenState: 3automaticTransitionFromOpenToHalfOpenEnabled: truewaitDurationInOpenState: 5sfailureRateThreshold: 50slowCallRateThreshold: 100slowCallDurationThreshold: 2s
在代码中使用:
@CircuitBreaker(name = "userService", fallbackMethod = "getUserFallback")
public User getUser(Long id) {return userClient.getUserById(id);
}public User getUserFallback(Long id, Exception e) {log.error("获取用户信息失败,进入服务降级", e);return new User(id, "默认用户", 0);
}
2. 舱壁模式(Bulkhead)
舱壁模式限制对特定服务的并发调用数,防止单个服务故障影响整个系统资源。
配置:
resilience4j:bulkhead:instances:userService:maxConcurrentCalls: 10maxWaitDuration: 1s
使用方式:
@Bulkhead(name = "userService", fallbackMethod = "getUserFallback")
public User getUser(Long id) {return userClient.getUserById(id);
}
3. 超时处理(TimeLimiter)
防止长时间运行的调用阻塞资源:
resilience4j:timelimiter:instances:userService:timeoutDuration: 2scancelRunningFuture: true
代码实现:
@TimeLimiter(name = "userService", fallbackMethod = "getUserFallback")
public CompletableFuture<User> getUserWithTimeout(Long id) {return CompletableFuture.supplyAsync(() -> userClient.getUserById(id));
}
4. 重试机制(Retry)
当服务调用失败时进行重试:
resilience4j:retry:instances:userService:maxAttempts: 3waitDuration: 1sretryExceptions:- org.springframework.web.client.HttpServerErrorExceptionignoreExceptions:- java.util.NoSuchElementException
代码实现:
@Retry(name = "userService", fallbackMethod = "getUserFallback")
public User getUserWithRetry(Long id) {return userClient.getUserById(id);
}
5. Feign 客户端降级
为 Feign 客户端配置服务降级:
@FeignClient(name = "user-service", fallback = UserClientFallback.class)
public interface UserClient {@GetMapping("/api/users/{id}")User getUserById(@PathVariable("id") Long id);
}@Component
public class UserClientFallback implements UserClient {@Overridepublic User getUserById(Long id) {return new User(id, "默认降级用户", 0);}
}
配置 Feign:
feign:circuitbreaker:enabled: true
6. 集成服务降级与监控
使用 Spring Boot Actuator 监控断路器状态:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
配置监控端点:
management:endpoints:web:exposure:include: health,info,circuitbreakersendpoint:health:show-details: alwayshealth:circuitbreakers:enabled: true
部署运行
- 构建各模块:
mvn clean package
- 启动顺序:Eureka Server > Config Server > 微服务 > Gateway
- 访问 Eureka 控制台:
http://localhost:8761
- 通过网关访问服务:
http://localhost:8080/api/users/1
总结
Spring Cloud 提供了构建微服务架构的完整解决方案,通过服务降级策略可以有效提高系统的稳定性和可用性。在微服务架构中,服务降级是必不可少的弹性设计,它确保了当部分服务不可用时,系统依然能够提供基本功能,避免级联故障导致整个系统瘫痪。实际生产环境中,还需根据业务需求和服务特性合理配置断路器阈值、超时时间和重试策略,同时结合监控系统实时关注服务健康状态。