当前位置: 首页 > news >正文

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 服务注册中心

  1. 添加依赖:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
  1. 配置 application.yml
server:port: 8761eureka:client:register-with-eureka: falsefetch-registry: false
  1. 启动类添加 @EnableEurekaServer 注解

步骤三:配置中心

  1. 添加依赖:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-config-server</artifactId>
</dependency>
  1. 配置 application.yml
server:port: 8888spring:cloud:config:server:git:uri: https://github.com/your-repo/config-repodefault-label: main
  1. 启动类添加 @EnableConfigServer 注解

步骤四:API 网关

  1. 添加依赖:
<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>
  1. 配置路由:
spring:cloud:gateway:routes:- id: user-serviceuri: lb://user-servicepredicates:- Path=/api/users/**- id: order-serviceuri: lb://order-servicepredicates:- Path=/api/orders/**

步骤五:微服务实现

  1. 创建公共模块依赖:
<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>
  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.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

部署运行

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

总结

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

相关文章:

  • 非线性1 修改
  • 23种设计模式解释+记忆
  • 5.18本日总结
  • VMware虚拟机磁盘扩容与LVM分区操作指南
  • GC全场景分析
  • Redis进阶知识
  • 服务端高并发分布式结构演进之路
  • 51单片机,两路倒计时,LCD1602 ,Proteus仿真
  • ubuntu的虚拟机上的网络图标没有了
  • Go语言中函数 vs 方法
  • STM32项目实战:ADC采集
  • Gartner《如何将生成式人工智能(GenAI)集成到应用架构》学习心得
  • elementplus menu 设置 activeindex
  • 探索用户行为数据分析——从基础查询到高级分析 【GaussDB(for MySQL)】
  • DeepSeek本地部署全攻略:从零搭建到Web可视化及数据训练
  • Java程序员学AI(一)
  • Linux(2)——shell原理及Linux中的权限
  • GLPK(GNU线性规划工具包)中建模语言MathProg的使用
  • MySQL 数据库备份与还原
  • Python训练营打卡 Day29
  • 上海浦江游览南拓新航线首航,途经前滩、世博文化公园等景点
  • 旅马大熊猫“福娃”“凤仪”平安回国
  • 国际博物馆日|航海博物馆:穿梭于海洋神话与明代造船工艺间
  • 北京韩美林艺术馆党支部书记郭莹病逝,终年40岁
  • 通用汽车回应进口车业务调整传闻:因经济形势变化重组,致力于在中国持续发展
  • 工商银行杭州金融研修院原院长蒋伟被“双开”