微服务架构中的稳定性保障:服务熔断、降级和限流策略详解

2024-12-27 14:14 更新

大家好,我是V哥,国足0-7不敌日本,创下12年来最大惨败,真的好久不看球赛了,我关心的是,作为国内唯一一家转播平台爱奇艺体育昨天崩了,官方道歉文中解释由于瞬时流量过大导致,这让我想起服务熔断、降级和限流是微服务架构中用于提高系统稳定性和可用性的三种关键策略。

介绍

服务熔断(Circuit Breaker)

服务熔断是一种防止服务故障蔓延的机制。它的概念来源于电力系统中的熔断器,当电流超过电路的承载能力时,熔断器会自动断开电路,以防止火灾等严重事故的发生。

在软件架构中,熔断器模式通常用于处理服务调用链中的远程服务调用。当某个服务调用失败的次数超过预设阈值时,熔断器会“断开”,暂时停止对该服务的调用。这样,系统可以快速失败,避免长时间的等待或大量的错误,从而保持系统的稳定性。在熔断期间,通常会提供一个备用的行为或返回一个友好的错误信息。

服务降级(Service Degradation)

服务降级是一种在系统负载过高或某些服务不可用时,临时关闭一些功能或降低服务标准的策略,以保证核心业务的正常运行。

在一个电商平台中,当遇到流量高峰时,可能会暂时关闭一些非核心功能,如商品推荐、优惠券发放等,以减轻服务器压力。或者,当支付服务不可用时,系统可能会允许用户将商品加入购物车,但暂时无法完成购买。

服务降级的目的是牺牲一部分用户体验,以确保系统不会因为过载而完全崩溃。

服务限流(Rate Limiting)

服务限流是一种控制服务调用频率的策略,以保护系统不被过量的请求压垮。

限流可以通过各种方式实现,例如:

  • 令牌桶:按照固定速率向桶中添加令牌,每次请求需要消耗一个令牌。
  • 漏桶:请求以固定速率从桶中流出,如果流出速度跟不上请求速度,多余的请求会被拒绝。
  • 固定窗口计数器:在固定时间窗口内计数请求次数,超过限制则拒绝服务。

限流可以应用于API网关,以控制对下游服务的访问频率,也可以应用于服务内部,以控制处理请求的速度。

高并发的电商购物车服务案例

假设在一个高并发的电商购物车服务案例,实现服务熔断、降级和限流。我们将使用Spring Boot和Spring Cloud Alibaba Sentinel来实现这些功能。

1. 项目结构

假设我们的项目结构如下:

  1. shopping-cart-service
  2. ├── pom.xml
  3. ├── src
  4. ├── main
  5. ├── java
  6. └── com
  7. └── example
  8. └── shoppingcart
  9. ├── ShoppingCartApplication.java
  10. ├── controller
  11. └── ShoppingCartController.java
  12. ├── service
  13. └── ShoppingCartService.java
  14. └── config
  15. └── SentinelConfig.java
  16. └── resources
  17. ├── application.yml
  18. └── flow-rules.json
  19. └── .gitignore

2. 添加依赖

pom.xml中添加Spring Boot和Spring Cloud Alibaba Sentinel依赖:

  1. <dependencies>
  2. <!-- Spring Boot Starter Web -->
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-web</artifactId>
  6. </dependency>
  7. <!-- Spring Cloud Alibaba Sentinel -->
  8. <dependency>
  9. <groupId>com.alibaba.cloud</groupId>
  10. <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
  11. </dependency>
  12. <!-- Spring Boot Starter Actuator -->
  13. <dependency>
  14. <groupId>org.springframework.boot</groupId>
  15. <artifactId>spring-boot-starter-actuator</artifactId>
  16. </dependency>
  17. </dependencies>
  18. <dependencyManagement>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.cloud</groupId>
  22. <artifactId>spring-cloud-dependencies</artifactId>
  23. <version>Hoxton.SR9</version>
  24. <type>pom</type>
  25. <scope>import</scope>
  26. </dependency>
  27. <dependency>
  28. <groupId>com.alibaba.cloud</groupId>
  29. <artifactId>spring-cloud-alibaba-dependencies</artifactId>
  30. <version>2.2.5.RELEASE</version>
  31. <type>pom</type>
  32. <scope>import</scope>
  33. </dependency>
  34. </dependencies>

3. 应用主类

ShoppingCartApplication.java中创建Spring Boot应用:

  1. package com.example.shoppingcart;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class ShoppingCartApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(ShoppingCartApplication.class, args);
  8. }
  9. }

4. 配置文件

application.yml中配置Sentinel Dashboard地址:

  1. server:
  2. port: 8080
  3. spring:
  4. application:
  5. name: shopping-cart-service
  6. spring:
  7. cloud:
  8. sentinel:
  9. transport:
  10. dashboard: localhost:8080
  11. datasource:
  12. ds1:
  13. type: file
  14. data-id: ${spring.application.name}-flow-rules
  15. rule-type: flow
  16. url: file:///path/to/your/flow-rules.json

5. 熔断、降级和限流规则

flow-rules.json中配置熔断、降级和限流规则:

  1. [
  2. {
  3. "resource": "addCart",
  4. "limitApp": "default",
  5. "grade": 1,
  6. "strategy": 0,
  7. "controlBehavior": 0,
  8. "threshold": 10,
  9. "action": 1
  10. },
  11. {
  12. "resource": "addCart",
  13. "limitApp": "default",
  14. "grade": 0,
  15. "strategy": 0,
  16. "controlBehavior": 1,
  17. "threshold": 5,
  18. "action": 1
  19. },
  20. {
  21. "resource": "addCart",
  22. "limitApp": "default",
  23. "grade": 0,
  24. "strategy": 0,
  25. "controlBehavior": 0,
  26. "threshold": 20,
  27. "action": 2
  28. }
  29. ]

6. 控制器

ShoppingCartController.java中创建REST API:

  1. package com.example.shoppingcart.controller;
  2. import com.alibaba.csp.sentinel.Entry;
  3. import com.alibaba.csp.sentinel.SphU;
  4. import com.alibaba.csp.sentinel.slots.block.BlockException;
  5. import com.example.shoppingcart.service.ShoppingCartService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.bind.annotation.RestController;
  10. @RestController
  11. public class ShoppingCartController {
  12. @Autowired
  13. private ShoppingCartService shoppingCartService;
  14. @GetMapping("/addCart")
  15. public String addCart(@RequestParam String productId, @RequestParam int quantity) {
  16. try (Entry entry = SphU.entry("addCart")) {
  17. return shoppingCartService.addCart(productId, quantity);
  18. } catch (BlockException ex) {
  19. return shoppingCartService.fallback();
  20. }
  21. }
  22. }

7. 服务

ShoppingCartService.java中实现业务逻辑:

  1. package com.example.shoppingcart.service;
  2. public class ShoppingCartService {
  3. public String addCart(String productId, int quantity) {
  4. // 模拟业务逻辑
  5. if (quantity > 10) {
  6. throw new RuntimeException("Quantity too large");
  7. }
  8. return "Added " + quantity + " of " + productId + " to cart";
  9. }
  10. public String fallback() {
  11. return "Cart service is temporarily unavailable";
  12. }
  13. }

8. 配置类

SentinelConfig.java中配置Sentinel规则:

  1. package com.example.shoppingcart.config;
  2. import com.alibaba.csp.sentinel.init.InitConfig;
  3. import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
  4. import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
  5. import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
  6. import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. @Configuration
  12. public class SentinelConfig {
  13. @Bean
  14. public InitConfig initConfig() {
  15. InitConfig initConfig = new InitConfig();
  16. initConfig.setDataSource("file", "classpath:flow-rules.json");
  17. return initConfig;
  18. }
  19. @Bean
  20. public List<FlowRule> flowRules() {
  21. List<FlowRule> rules = new ArrayList<>();
  22. FlowRule rule = new FlowRule("addCart");
  23. rule.setCount(10); // 限流阈值
  24. rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // QPS模式
  25. rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); // 直接拒绝
  26. rules.add(rule);
  27. return rules;
  28. }
  29. @Bean
  30. public List<DegradeRule> degradeRules() {
  31. List<DegradeRule> rules = new ArrayList<>();
  32. DegradeRule rule = new DegradeRule("addCart");
  33. rule.setGrade(RuleConstant.DEGRADE_GRADE_RT); // 响应时间模式
  34. rule.setCount(500); // 响应时间阈值
  35. rule.setTimeWindow(10); // 时间窗口
  36. rule.setMinRequestAmount(5); // 最小请求量
  37. rules.add(rule);
  38. return rules;
  39. }
  40. }

9. 启动Sentinel Dashboard

确保你已经启动了Sentinel Dashboard,可以通过以下命令启动:

  1. java -jar sentinel-dashboard.jar

10. 运行应用

运行ShoppingCartApplication,然后通过浏览器或Postman测试API:

  1. http://localhost:8080/addCart?productId=123&quantity=5

解释一下

  1. 熔断:当addCart方法的调用次数超过10次时,Sentinel会触发熔断,直接返回降级逻辑。
  2. 降级:当addCart方法的响应时间超过500ms,或者调用次数超过5次时,Sentinel会触发降级,返回降级逻辑。
  3. 限流:当addCart方法的调用次数超过10次时,Sentinel会触发限流,直接拒绝请求。

通过这些配置,我们可以在高并发场景下保护我们的服务,避免系统过载。

最后

  • 熔断:当服务不可用时,快速失败,避免系统过载。
  • 降级:在系统压力较大时,暂时关闭或降低非核心服务的质量,保证核心服务的可用性。
  • 限流:控制请求的速率,防止系统因请求过多而崩溃。

这三种策略通常结合使用,以提高大型分布式系统的稳定性和可用性。

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号