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.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>

步骤二:Eureka 服务注册中心

  1. 添加依赖:
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-netflix-eureka-serverartifactId>
dependency>
  1. 配置 application.yml
server:
  port: 8761

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
  1. 启动类添加 @EnableEurekaServer 注解

步骤三:配置中心

  1. 添加依赖:
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-config-serverartifactId>
dependency>
  1. 配置 application.yml
server:
  port: 8888

spring:
  cloud:
    config:
      server:
        git:
          uri: https://github.com/your-repo/config-repo
          default-label: main
  1. 启动类添加 @EnableConfigServer 注解

步骤四:API 网关

  1. 添加依赖:
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-gatewayartifactId>
dependency>
<dependency>
    <groupId>org.springframework.cloudgroupId>
    <artifactId>spring-cloud-starter-netflix-eureka-clientartifactId>
dependency>
  1. 配置路由:
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/**

步骤五:微服务实现

  1. 创建公共模块依赖:
<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>
  1. 服务调用示例:
@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.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);
}

2. 舱壁模式(Bulkhead)

舱壁模式限制对特定服务的并发调用数,防止单个服务故障影响整个系统资源。

配置:

resilience4j:
  bulkhead:
    instances:
      userService:
        maxConcurrentCalls: 10
        maxWaitDuration: 1s

使用方式:

@Bulkhead(name = "userService", fallbackMethod = "getUserFallback")
public User getUser(Long id) {
    return userClient.getUserById(id);
}

3. 超时处理(TimeLimiter)

防止长时间运行的调用阻塞资源:

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));
}

4. 重试机制(Retry)

当服务调用失败时进行重试:

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);
}

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 {
    @Override
    public User getUserById(Long id) {
        return new User(id, "默认降级用户", 0);
    }
}

配置 Feign:

feign:
  circuitbreaker:
    enabled: true

6. 集成服务降级与监控

使用 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

部署运行

  1. 构建各模块:mvn clean package
  2. 启动顺序:Eureka Server > Config Server > 微服务 > Gateway
  3. 访问 Eureka 控制台:http://localhost:8761
  4. 通过网关访问服务:http://localhost:8080/api/users/1

总结

Spring Cloud 提供了构建微服务架构的完整解决方案,通过服务降级策略可以有效提高系统的稳定性和可用性。在微服务架构中,服务降级是必不可少的弹性设计,它确保了当部分服务不可用时,系统依然能够提供基本功能,避免级联故障导致整个系统瘫痪。实际生产环境中,还需根据业务需求和服务特性合理配置断路器阈值、超时时间和重试策略,同时结合监控系统实时关注服务健康状态。

你可能感兴趣的:(实战进阶,spring,cloud,spring,后端)