Spring Cloud 是基于 Spring Boot 构建的微服务框架,提供了一套完整的微服务解决方案。它利用 Spring Boot 的开发便利性,并通过各种组件简化分布式系统的开发。
spring-cloud-demo/
├── eureka-server/ # 服务注册中心
├── config-server/ # 配置中心
├── gateway-service/ # API 网关
├── user-service/ # 用户服务
├── order-service/ # 订单服务
└── pom.xml # 父 POM
创建 pom.xml,管理依赖版本:
<parent>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-parentartifactId>
<version>2.6.7version>
parent>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-dependenciesartifactId>
<version>2021.0.2version>
<type>pomtype>
<scope>importscope>
dependency>
dependencies>
dependencyManagement>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
dependency>
application.yml:server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
@EnableEurekaServer 注解<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-config-serverartifactId>
dependency>
application.yml:server:
port: 8888
spring:
cloud:
config:
server:
git:
uri: https://github.com/your-repo/config-repo
default-label: main
@EnableConfigServer 注解<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-gatewayartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
- id: order-service
uri: lb://order-service
predicates:
- Path=/api/orders/**
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-webartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-openfeignartifactId>
dependency>
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4jartifactId>
dependency>
@FeignClient(name = "user-service")
public interface UserClient {
@GetMapping("/api/users/{id}")
User getUserById(@PathVariable("id") Long id);
}
在微服务架构中,服务降级是保障系统可用性的关键策略。Spring Cloud 提供了多种服务降级机制,主要通过 Resilience4j(替代了之前的 Hystrix)实现。
断路器模式用于防止服务级联故障。当某个服务频繁失败时,断路器会"断开",快速失败而不是等待超时。
添加依赖:
<dependency>
<groupId>org.springframework.cloudgroupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4jartifactId>
dependency>
配置断路器:
resilience4j:
circuitbreaker:
instances:
userService:
registerHealthIndicator: true
slidingWindowSize: 10
minimumNumberOfCalls: 5
permittedNumberOfCallsInHalfOpenState: 3
automaticTransitionFromOpenToHalfOpenEnabled: true
waitDurationInOpenState: 5s
failureRateThreshold: 50
slowCallRateThreshold: 100
slowCallDurationThreshold: 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);
}
舱壁模式限制对特定服务的并发调用数,防止单个服务故障影响整个系统资源。
配置:
resilience4j:
bulkhead:
instances:
userService:
maxConcurrentCalls: 10
maxWaitDuration: 1s
使用方式:
@Bulkhead(name = "userService", fallbackMethod = "getUserFallback")
public User getUser(Long id) {
return userClient.getUserById(id);
}
防止长时间运行的调用阻塞资源:
resilience4j:
timelimiter:
instances:
userService:
timeoutDuration: 2s
cancelRunningFuture: true
代码实现:
@TimeLimiter(name = "userService", fallbackMethod = "getUserFallback")
public CompletableFuture<User> getUserWithTimeout(Long id) {
return CompletableFuture.supplyAsync(() -> userClient.getUserById(id));
}
当服务调用失败时进行重试:
resilience4j:
retry:
instances:
userService:
maxAttempts: 3
waitDuration: 1s
retryExceptions:
- org.springframework.web.client.HttpServerErrorException
ignoreExceptions:
- java.util.NoSuchElementException
代码实现:
@Retry(name = "userService", fallbackMethod = "getUserFallback")
public User getUserWithRetry(Long id) {
return userClient.getUserById(id);
}
为 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 {
@Override
public User getUserById(Long id) {
return new User(id, "默认降级用户", 0);
}
}
配置 Feign:
feign:
circuitbreaker:
enabled: true
使用 Spring Boot Actuator 监控断路器状态:
<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-actuatorartifactId>
dependency>
配置监控端点:
management:
endpoints:
web:
exposure:
include: health,info,circuitbreakers
endpoint:
health:
show-details: always
health:
circuitbreakers:
enabled: true
mvn clean packagehttp://localhost:8761http://localhost:8080/api/users/1Spring Cloud 提供了构建微服务架构的完整解决方案,通过服务降级策略可以有效提高系统的稳定性和可用性。在微服务架构中,服务降级是必不可少的弹性设计,它确保了当部分服务不可用时,系统依然能够提供基本功能,避免级联故障导致整个系统瘫痪。实际生产环境中,还需根据业务需求和服务特性合理配置断路器阈值、超时时间和重试策略,同时结合监控系统实时关注服务健康状态。