SpringCloudAlibaba微服务架构搭建(五)Sentinel 详细教程(实战教程)

1. 介绍

1.1 什么是Spring Cloud Alibaba Sentinel?

​ Spring Cloud Alibaba Sentinel(简称Sentinel)是一款开源的流量控制和熔断降级框架,专注于提供微服务架构中的流量控制、熔断降级、系统自适应保护等功能。它是阿里巴巴集团开发的一款分布式系统的容错框架,旨在解决微服务架构中的服务雪崩问题,提高系统的稳定性和可靠性。
在这里插入图片描述

1.2 为什么需要使用Sentinel?

​ 使用Sentinel的主要原因是为了增加分布式系统的稳定性、可靠性和弹性,以及保护系统免受异常情况和过载的影响。以下是一些需要使用Sentinel的理由:

  1. 防止服务雪崩:在微服务架构中,一个服务的故障可能会导致连锁反应,影响到整个系统。通过使用Sentinel的流量控制和熔断降级功能,可以在服务出现异常或响应时间过长时,快速限制流量或熔断降级,从而避免服务雪崩的发生。
  2. 保护关键服务:系统中通常有一些关键的服务,它们可能被大量请求访问,容易出现过载。Sentinel可以对这些关键服务进行流量控制,确保它们能够正常运行,并防止被过多的请求压垮。
  3. 提高用户体验:通过对响应时间、流量等指标进行监控和限制,可以确保系统的响应速度在可接受范围内,提供更好的用户体验。
  4. 避免资源耗尽:分布式系统中的资源(例如线程、连接、内存等)是有限的,过多的请求可能会耗尽这些资源。Sentinel的流量控制功能可以帮助系统避免资源耗尽,保持稳定性。
  5. 自动化的容错处理:Sentinel的熔断降级功能可以在服务出现异常时自动切换到备用逻辑,而不是持续提供低质量的服务。这有助于减少用户受到的影响,并为问题的排查和修复争取时间。
  6. 动态调整策略:Sentinel允许根据实际情况动态调整流控和熔断规则,从而可以根据负载、业务变化等动态地调整系统的行为,提高系统的适应性。
  7. 实时监控和警报:Sentinel提供了实时的监控和统计功能,可以帮助开发人员及时了解系统的运行情况,发现问题并采取措施。此外,Sentinel还可以配合警报系统,及时通知开发人员系统出现异常。
    在这里插入图片描述

1.3 Sentinel的核心功能和特点

  1. 流量控制:Sentinel可以对服务的入口流量进行限制,防止服务被过多的请求打垮。它支持基于QPS(每秒请求数)和线程数的流量控制,以及热点参数限流,可以根据具体业务场景进行配置。
  2. 熔断降级:Sentinel可以在服务出现异常、响应时间过长或其他问题时,自动触发熔断降级策略,防止问题扩散到整个系统。它支持基于响应时间、异常比例等指标进行熔断降级。
  3. 系统自适应保护:Sentinel可以根据系统的负载情况和资源使用情况,自动调整流量控制和熔断降级的策略,保护系统免受过载和资源耗尽的影响。
  4. 实时监控和统计:Sentinel提供了实时的监控和统计功能,可以查看服务的流量、响应时间、异常信息等,帮助开发人员及时发现问题并进行处理。
  5. 控制台:Sentinel提供了一个可视化的控制台,用于配置规则、查看监控数据和管理流控、降级等策略。
  6. 与Spring Cloud集成:Sentinel与Spring Cloud技术栈无缝集成,可以轻松地在Spring Cloud微服务中使用Sentinel来实现流量控制和熔断降级。

2. 快速入门

  • 依赖引入

    在你的 Spring Cloud 项目的 Maven 或 Gradle 配置文件中,添加以下依赖:

    Maven:

    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
    

    Gradle:

    implementation 'com.alibaba.cloud:spring-cloud-starter-alibaba-sentinel'
    
  • 配置初始化

    在你的 Spring Boot 应用的配置文件(比如 application.propertiesapplication.yml)中,添加 Sentinel 的配置:

    spring:
      cloud:
        sentinel:
          transport:
            dashboard: localhost:8080 # Sentinel Dashboard 地址
          eager: true # 开启 SentinelEager 模式,即提前初始化 Sentinel 监听器
    
  • 注解配置

    在你的 Spring Boot 主类上添加 @EnableCircuitBreaker 注解,启用熔断器功能。示例:

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
    
    @SpringBootApplication
    @EnableCircuitBreaker
    public class YourApplication {
        public static void main(String[] args) {
            SpringApplication.run(YourApplication.class, args);
        }
    }
    
  • 使用注解进行流控和降级配置

    在你的业务方法上添加 @SentinelResource 注解,进行流控和降级配置。示例:

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock")
        public String demoMethod() {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义流控降级处理方法
        public String handleBlock(Throwable e) {
            return "Blocked due to flow control or circuit breaker!";
        }
    }
    
    
  • Dashboard的启动和使用

    下载 Sentinel Dashboard 的 jar 包并运行,可以通过以下命令启动:

    java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar
    

    ​ 在浏览器中访问 http://localhost:8080,你将看到 Sentinel Dashboard 的界面。在 Dashboard 中,你可以配置流控规则、熔断规则,查看实时监控数据等。

3. 流控规则

Field说明默认值
resource资源名,资源名是限流规则的作用对象
count限流阈值
grade限流阈值类型,QPS 模式(1)或并发线程数模式(0)QPS 模式
limitApp流控针对的调用来源default,代表不区分调用来源
strategy调用关系限流策略:直接、链路、关联根据资源本身(直接)
controlBehavior流控效果(直接拒绝/WarmUp/匀速+排队等待),不支持按调用关系限流直接拒绝
clusterMode是否集群限流
  • 单机流控

    单机流控是对单个服务实例的流量进行控制,防止某个实例被过多的请求压垮。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock")
        public String demoMethod() {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义流控降级处理方法
        public String handleBlock(Throwable e) {
            return "Blocked due to flow control!";
        }
    }
    
  • 集群流控

    集群流控是对多个服务实例的流量进行控制,防止整个服务集群被过多的请求压垮。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock")
        public String demoMethod() {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义流控降级处理方法
        public String handleBlock(Throwable e) {
            return "Blocked due to cluster flow control!";
        }
    }
    
  • 热点参数限流

    热点参数限流允许你根据某个参数的值来限制流量,防止热点参数的请求压垮系统。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock")
        public String demoMethod(String parameter) {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义流控降级处理方法
        public String handleBlock(String parameter, Throwable e) {
            return "Blocked due to parameter hot spot flow control!";
        }
    }
    
  • 控制台配置流控规则

    你可以使用 Sentinel 控制台来配置流控规则,以下是一个简单的代码示例,展示如何通过控制台配置流控规则:

    在启动类中添加以下配置类:

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
    import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
    import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
    import java.util.ArrayList;
    import java.util.List;
    
    @Configuration
    public class SentinelConfig {
    
        @Bean
        public SentinelResourceAspect sentinelResourceAspect() {
            return new SentinelResourceAspect();
        }
    
        @PostConstruct
        public void initFlowRules() {
            List<FlowRule> rules = new ArrayList<>();
            FlowRule rule = new FlowRule();
            rule.setResource("demoResource"); // 资源名称,对应 @SentinelResource 注解的 value 值
            rule.setCount(10); // QPS 阈值
            rule.setGrade(RuleConstant.FLOW_GRADE_QPS); // 限流规则类型
            rules.add(rule);
            FlowRuleManager.loadRules(rules);
        }
    }
    

在这里插入图片描述

4. 降级规则

  • RT(平均响应时间)降级

    RT 降级是根据服务的平均响应时间来触发降级,当服务的平均响应时间超过设定的阈值时,将触发降级。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义流控降级处理方法
        public String handleBlock(Throwable e) {
            return "Blocked due to RT (response time) degradation!";
        }
    
        // 定义降级回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to RT (response time) degradation!";
        }
    }
    
    
  • 异常比例降级

    异常比例降级是根据异常比例来触发降级,当服务的异常比例超过设定的阈值时,将触发降级。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑
            if (Math.random() > 0.5) {
                throw new RuntimeException("Exception for testing");
            }
            return "Hello, Sentinel!";
        }
    
        // 定义流控降级处理方法
        public String handleBlock(Throwable e) {
            return "Blocked due to exception ratio degradation!";
        }
    
        // 定义降级回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to exception ratio degradation!";
        }
    }
    
  • 异常数降级

    异常数降级是根据异常数量来触发降级,当服务的异常数量超过设定的阈值时,将触发降级。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        private static int exceptionCount = 0;
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑
            if (Math.random() > 0.5) {
                exceptionCount++;
                throw new RuntimeException("Exception for testing");
            }
            return "Hello, Sentinel!";
        }
    
        // 定义流控降级处理方法
        public String handleBlock(Throwable e) {
            return "Blocked due to exception count degradation!";
        }
    
        // 定义降级回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to exception count degradation!";
        }
    }
    
  • 控制台配置降级规则

    • 启动 Sentinel 控制台,可以使用以下命令:

      java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar
      
    • 在浏览器中访问 http://localhost:8080,登录 Sentinel 控制台。

    • 在控制台中选择 “流控规则” 选项,点击 “新增规则”。

    • 根据需要选择降级规则类型,比如 “平均响应时间”、“异常比例” 或 “异常数”,然后配置阈值、触发策略等。

    • 配置完成后,点击 “添加” 按钮,即可在控制台中看到已配置的降级规则。

5. 熔断规则

  • 慢调用比例触发熔断

    慢调用比例触发熔断是根据请求的平均响应时间来触发熔断,当服务的慢调用比例超过设定的阈值时,将触发熔断。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑,模拟慢调用
            try {
                Thread.sleep(1000); // 模拟耗时操作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello, Sentinel!";
        }
    
        // 定义熔断降级处理方法
        public String handleBlock(Throwable e) {
            return "Circuit breaker triggered due to slow call ratio!";
        }
    
        // 定义熔断回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to slow call ratio!";
        }
    }
    

    在这里插入图片描述

  • 快速失败触发熔断

    快速失败触发熔断是当请求被流控后立即失败,无需等待超时。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义熔断降级处理方法
        public String handleBlock(Throwable e) {
            return "Circuit breaker triggered due to quick failure!";
        }
    
        // 定义熔断回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to quick failure!";
        }
    }
    
  • 异常比例触发熔断

    异常比例触发熔断是根据请求的异常比例来触发熔断,当服务的异常比例超过设定的阈值时,将触发熔断。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑,模拟异常
            if (Math.random() > 0.5) {
                throw new RuntimeException("Exception for testing");
            }
            return "Hello, Sentinel!";
        }
    
        // 定义熔断降级处理方法
        public String handleBlock(Throwable e) {
            return "Circuit breaker triggered due to exception ratio!";
        }
    
        // 定义熔断回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to exception ratio!";
        }
    }
    
  • 控制台配置熔断规则

    当使用 Spring Cloud Alibaba Sentinel 进行熔断规则的讲解时,需要了解慢调用比例触发熔断、快速失败触发熔断、异常比例触发熔断以及如何在 Sentinel 控制台中配置熔断规则。以下是详细的讲解、操作步骤和代码案例。

    1. 慢调用比例触发熔断:

    慢调用比例触发熔断是根据请求的平均响应时间来触发熔断,当服务的慢调用比例超过设定的阈值时,将触发熔断。

    javaCopy code
    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑,模拟慢调用
            try {
                Thread.sleep(1000); // 模拟耗时操作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Hello, Sentinel!";
        }
    
        // 定义熔断降级处理方法
        public String handleBlock(Throwable e) {
            return "Circuit breaker triggered due to slow call ratio!";
        }
    
        // 定义熔断回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to slow call ratio!";
        }
    }
    

    2. 快速失败触发熔断:

    快速失败触发熔断是当请求被流控后立即失败,无需等待超时。

    javaCopy code
    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义熔断降级处理方法
        public String handleBlock(Throwable e) {
            return "Circuit breaker triggered due to quick failure!";
        }
    
        // 定义熔断回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to quick failure!";
        }
    }
    

    3. 异常比例触发熔断:

    异常比例触发熔断是根据请求的异常比例来触发熔断,当服务的异常比例超过设定的阈值时,将触发熔断。

    javaCopy code
    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑,模拟异常
            if (Math.random() > 0.5) {
                throw new RuntimeException("Exception for testing");
            }
            return "Hello, Sentinel!";
        }
    
        // 定义熔断降级处理方法
        public String handleBlock(Throwable e) {
            return "Circuit breaker triggered due to exception ratio!";
        }
    
        // 定义熔断回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to exception ratio!";
        }
    }
    

    4. 控制台配置熔断规则:

    要在 Sentinel 控制台中配置熔断规则,需要执行以下步骤:

    • 启动 Sentinel 控制台,可以使用以下命令:

      java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar
      
    • 在浏览器中访问 http://localhost:8080,登录 Sentinel 控制台。

    • 在控制台中选择 “熔断降级” 选项,点击 “新增规则”。

    • 根据需要选择熔断规则类型,比如 “慢调用比例”、“快速失败” 或 “异常比例”,然后配置阈值、触发策略等。

    • 配置完成后,点击 “添加” 按钮,即可在控制台中看到已配置的熔断规则。
      在这里插入图片描述

6. 系统自适应保护

  • QPS自适应

    QPS 自适应规则根据系统的 QPS(每秒请求数)来自动调整流量控制规则,以保护系统免受过载的影响。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义流控降级处理方法
        public String handleBlock(Throwable e) {
            return "Blocked due to QPS adaptation!";
        }
    
        // 定义降级回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to QPS adaptation!";
        }
    }
    

    在这里插入图片描述

  • 平均响应时间自适应

    平均响应时间自适应规则根据系统的平均响应时间来自动调整流量控制规则,以保证系统的稳定性。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义流控降级处理方法
        public String handleBlock(Throwable e) {
            return "Blocked due to average RT (response time) adaptation!";
        }
    
        // 定义降级回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to average RT (response time) adaptation!";
        }
    }
    
  • 线程数自适应

    线程数自适应规则根据系统的线程数来自动调整流量控制规则,以保证系统的稳定性和性能。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义流控降级处理方法
        public String handleBlock(Throwable e) {
            return "Blocked due to thread count adaptation!";
        }
    
        // 定义降级回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to thread count adaptation!";
        }
    }
    
    
  • 控制台配置自适应规则

    • 启动 Sentinel 控制台,可以使用以下命令:

      java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar
      
    • 在浏览器中访问 http://localhost:8080,登录 Sentinel 控制台。

    • 在控制台中选择 “系统自适应保护” 选项,点击 “新增规则”。

    • 根据需要选择自适应规则类型,比如 “QPS 自适应”、“平均响应时间自适应” 或 “线程数自适应”,然后配置阈值、触发策略等。

    • 配置完成后,点击 “添加” 按钮,即可在控制台中看到已配置的自适应规则。

7. 热点参数限流

  • 参数例外项配置

    热点参数限流可以根据方法的参数值来进行流量控制。你可以配置一些参数例外项,让这些参数的值不受限制。下面是一个例子,演示如何配置参数例外项。

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    import com.alibaba.csp.sentinel.slots.block.BlockException;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod(String parameter) {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义流控降级处理方法
        public String handleBlock(String parameter, BlockException ex) {
            return "Blocked due to parameter hot spot flow control!";
        }
    
        // 定义降级回退方法
        public String fallbackMethod(String parameter) {
            return "Fallback due to parameter hot spot flow control!";
        }
    }
    
  • 控制台配置热点参数规则

    • 启动 Sentinel 控制台,可以使用以下命令:

      java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar
      
    • 在浏览器中访问 http://localhost:8080,登录 Sentinel 控制台。

    • 在控制台中选择 “热点参数限流” 选项,点击 “新增规则”。

    • 配置资源名称,可以使用 @SentinelResource 注解中的 value 值,例如 “demoResource”。

    • 在 “参数例外项” 中,添加不需要限制的参数值。例如,配置参数名为 parameter,例外项值为 exceptionValue

    • 配置其他限流规则,如阈值、统计窗口等。

    • 配置完成后,点击 “添加” 按钮,即可在控制台中看到已配置的热点参数规则。

8. 集成Spring Cloud Alibab

  • 使用Sentinel作为Spring Cloud微服务的网关

    • 在 Spring Cloud Alibaba 中,可以使用 Nacos 作为服务注册和配置中心,结合 Gateway 实现网关限流。

      1. 创建一个 Spring Cloud Gateway 项目,引入依赖:

      Maven:

      <dependency>
          <groupId>org.springframework.cloud</groupId>
          <artifactId>spring-cloud-starter-gateway</artifactId>
      </dependency>
      <dependency>
          <groupId>com.alibaba.cloud</groupId>
          <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
      </dependency>
      
      1. 配置 Sentinel 的流控规则:

      在 Nacos 配置中心中配置 Sentinel 的流控规则,例如,配置一个限制访问 /api/hello 的规则。

      spring:
        cloud:
          sentinel:
            transport:
              dashboard: localhost:8080
      
      1. 创建一个简单的 Gateway 配置类:

        import org.springframework.beans.factory.annotation.Value;
        import org.springframework.cloud.gateway.filter.GlobalFilter;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        import reactor.core.publisher.Mono;
        import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
        import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
        import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
        
        @Configuration
        public class GatewayConfig {
        
            @Value("${spring.cloud.sentinel.transport.dashboard}")
            private String dashboard;
        
            @Bean
            public GlobalFilter sentinelGatewayFilter() {
                return new SentinelGatewayFilter();
            }
        
            @PostConstruct
            public void initBlockHandler() {
                BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) ->
                    Mono.fromCallable(() -> "Blocked by Sentinel: " + throwable.getClass().getSimpleName());
        
                GatewayCallbackManager.setBlockHandler(blockRequestHandler);
            }
        }
        

        以上配置启动成功后即整合完成,注意一定要启动sentinel服务!

  • 在RestTemplate中使用Sentinel

    • 在需要使用 RestTemplate 的微服务项目中,引入 Sentinel 依赖:

    Maven:

    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
    
    1. 配置 Sentinel 的流控规则,可以在 Nacos 配置中心中配置。

    2. 创建一个带有 Sentinel 流控保护的 RestTemplate 配置类:

      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.web.client.RestTemplate;
      import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate;
      
      @Configuration
      public class RestTemplateConfig {
      
          @Bean
          @SentinelRestTemplate
          public RestTemplate restTemplate() {
              return new RestTemplate();
          }
      }
      
    3. 在需要调用其他微服务的地方使用 RestTemplate:

      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.stereotype.Service;
      import org.springframework.web.client.RestTemplate;
      
      @Service
      public class MyService {
      
          @Autowired
          private RestTemplate restTemplate;
      
          public String callOtherService() {
              // 使用 RestTemplate 进行调用,会受到 Sentinel 流控保护
              return restTemplate.getForObject("http://other-service/api/hello", String.class);
          }
      }
      
      

      以上仅仅提供了基本代码案例和操作步骤,用于演示 Spring Cloud Alibaba 中集成 Sentinel,实际项目中还需要配置 Sentinel 控制台、Nacos 注册中心等。
      在这里插入图片描述

9. 与Nacos的集成

  • 使用Nacos配置Sentinel规则

    • Nacos 可以作为配置中心来管理 Sentinel 的规则配置

      1. 创建一个 Spring Cloud Alibaba Sentinel 项目,引入依赖:

      Maven:

      <dependency>
          <groupId>com.alibaba.cloud</groupId>
          <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
      </dependency>
      <dependency>
          <groupId>com.alibaba.cloud</groupId>
          <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
      </dependency>
      

      在 Nacos 配置中心中创建配置项,例如 sentinel-demo-rules.json,用于存储 Sentinel 的规则配置:

      [
        {
          "resource": "demoResource",
          "limitApp": "default",
          "grade": 1,
          "count": 10
        }
      ]
      
    • 在应用的 bootstrap.ymlbootstrap.properties 中配置 Nacos 作为配置中心:

    spring:
      cloud:
        nacos:
          config:
            server-addr: localhost:8848
            file-extension: json
            group: DEFAULT_GROUP
            namespace: your-namespace # 替换为你的命名空间
    
    • 在启动类中添加 @EnableNacosConfig 注解:
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.alibaba.nacos.config.EnableNacosConfig;
    
    @SpringBootApplication
    @EnableNacosConfig
    public class SentinelNacosDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SentinelNacosDemoApplication.class, args);
        }
    }
    
    1. 在需要使用 Sentinel 规则的地方,使用 @SentinelResource 注解,配置资源名与 Nacos 中的配置对应:
    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource")
        public String demoMethod() {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    }
    
    
  • 使用Nacos持久化Sentinel统计数据

    Nacos 可以作为数据持久化存储 Sentinel 的统计数据。

    1. 创建一个 Spring Cloud Alibaba Sentinel 项目,引入依赖:

    Maven:

    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>
    
    
    1. 在 Nacos 配置中心中创建配置项,例如 sentinel-metrics.yml,用于存储 Sentinel 的统计数据持久化配置:
    sentinel:
      transport:
        dashboard: localhost:8080
        nacos:
          server-addr: localhost:8848
          group-id: DEFAULT_GROUP
          namespace: your-namespace # 替换为你的命名空间
    
    
    1. 在启动类中添加 @EnableNacosConfig 注解:
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.alibaba.nacos.config.EnableNacosConfig;
    
    @SpringBootApplication
    @EnableNacosConfig
    public class SentinelNacosMetricsDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SentinelNacosMetricsDemoApplication.class, args);
        }
    }
    

    以上只是简单的 Spring Cloud Alibaba 中集成 Sentinel 和 Nacos 的规则配置和统计数据持久化,生产环境请根据实际业务配置。

10. Sentinel控制台

  • Dashboard的使用介绍

    Sentinel 控制台 Dashboard 提供了图表展示、规则配置、应用信息查看等功能,帮助你监控和管理微服务的流量控制和熔断降级等策略。

  • 控制台的监控和管理功能

    Sentinel 控制台 Dashboard 提供了以下主要功能:

    • 实时监控:可以查看微服务的实时流量、RT(响应时间)、QPS(每秒请求数)等信息。
    • 流控规则:可以配置和管理流控规则,包括单机流控、集群流控等。
    • 熔断降级规则:可以配置和管理熔断降级规则,包括慢调用比例、异常比例等。
    • 热点参数规则:可以配置和管理热点参数限流规则,保护指定参数。
    • 系统自适应保护规则:可以配置和管理系统自适应保护规则,保护系统稳定性。
    • 应用信息:查看微服务的基本信息,如应用名称、IP 端口等。

11. 最佳实践和注意事项

  • 避免单点故障

    • 避免单点故障: 在 Sentinel 控制台使用集群配置和数据持久化,确保高可用性,避免单点故障。
    • 规则配置的优先级: Sentinel 规则有多种类型(流控、降级、热点参数等),不同类型的规则之间会存在优先级。流控规则的优先级高于热点参数规则,降级规则的优先级高于流控规则。要仔细了解不同规则类型的优先级,确保配置生效。
    • 合理设置阈值和策略: 阈值设置过低可能导致正常流量被限制,阈值过高可能导致系统不稳定。选择合适的流控策略(直接、关联、链路等)以及降级策略(慢调用比例、异常比例等),根据业务特点进行设置。
    • 精细化限流和降级: 不要过度限制或降级所有请求,要根据不同的业务场景和资源特点,进行精细化的配置。
    • 监控和告警: 使用 Sentinel 控制台实时监控流量、响应时间等指标,并设置告警策略,及时发现问题并采取措施。
    • 持续优化规则: 随着业务的发展和变化,不断优化和调整规则,保持系统的稳定性和高可用性。
  • 如何处理降级和熔断

    在处理降级和熔断时,需要根据业务需求选择合适的策略和处理方法。以下是一些示例代码和操作步骤,用于演示如何处理降级和熔断。

    1. 处理降级:

      import org.springframework.stereotype.Service;
      import com.alibaba.csp.sentinel.annotation.SentinelResource;
      
      @Service
      public class MyService {
      
          @SentinelResource(value = "demoResource", fallback = "fallbackMethod")
          public String demoMethod() {
              // 业务逻辑
              return "Hello, Sentinel!";
          }
      
          // 定义降级回退方法
          public String fallbackMethod() {
              return "Fallback due to degradation!";
          }
      }
      
      
    2. 处理熔断:

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(value = "demoResource", blockHandler = "handleBlock", fallback = "fallbackMethod")
        public String demoMethod() {
            // 业务逻辑
            return "Hello, Sentinel!";
        }
    
        // 定义熔断降级处理方法
        public String handleBlock(Throwable e) {
            return "Circuit breaker triggered!";
        }
    
        // 定义降级回退方法
        public String fallbackMethod(Throwable e) {
            return "Fallback due to circuit breaker!";
        }
    }
    
    
  • 配置规则的优先级

    在 Sentinel 中,规则的优先级从高到低依次是:系统保护规则 > 流控规则 > 热点参数限流规则 > 授权规则 > 降级规则 > 熔断规则。

    系统保护规则是最高优先级,其次是流控规则,然后是热点参数限流规则,依此类推。如果存在多个规则,Sentinel 会根据优先级的顺序依次检查,一旦命中生效的规则,则不再继续匹配其他规则。

    以下是一个示例代码和操作步骤,演示如何设置不同类型规则的优先级。

    1. 创建一个 Spring Cloud Alibaba Sentinel 项目。

    2. 引入相关依赖,如 spring-cloud-starter-alibaba-sentinel

    3. 配置 Sentinel 控制台地址,在 application.propertiesapplication.yml 中添加:

      spring:
        cloud:
          sentinel:
            transport:
              dashboard: localhost:8080
      
      
    4. 创建一个 Service 类,配置不同类型的规则,设置优先级:

    import org.springframework.stereotype.Service;
    import com.alibaba.csp.sentinel.annotation.SentinelResource;
    
    @Service
    public class MyService {
    
        @SentinelResource(
            value = "systemRule",
            blockHandler = "systemRuleBlockHandler"
        )
        public String systemRuleDemo() {
            // 业务逻辑
            return "System Rule Demo";
        }
    
        @SentinelResource(
            value = "flowRule",
            blockHandler = "flowRuleBlockHandler"
        )
        public String flowRuleDemo() {
            // 业务逻辑
            return "Flow Rule Demo";
        }
    
        @SentinelResource(
            value = "hotParamRule",
            blockHandler = "hotParamRuleBlockHandler"
        )
        public String hotParamRuleDemo(String param) {
            // 业务逻辑
            return "Hot Param Rule Demo";
        }
    
        @SentinelResource(
            value = "degradeRule",
            blockHandler = "degradeRuleBlockHandler"
        )
        public String degradeRuleDemo() {
            // 业务逻辑
            return "Degrade Rule Demo";
        }
    
        @SentinelResource(
            value = "circuitBreakerRule",
            blockHandler = "circuitBreakerRuleBlockHandler"
        )
        public String circuitBreakerRuleDemo() {
            // 业务逻辑
            return "Circuit Breaker Rule Demo";
        }
    
        // 省略其他业务方法和降级处理方法
    }
    
    
    1. 配置降级处理方法:
    import org.springframework.stereotype.Component;
    import com.alibaba.csp.sentinel.slots.block.BlockException;
    
    @Component
    public class BlockHandler {
    
        public String systemRuleBlockHandler(BlockException ex) {
            return "Blocked by System Rule";
        }
    
        public String flowRuleBlockHandler(BlockException ex) {
            return "Blocked by Flow Rule";
        }
    
        public String hotParamRuleBlockHandler(String param, BlockException ex) {
            return "Blocked by Hot Param Rule";
        }
    
        public String degradeRuleBlockHandler(BlockException ex) {
            return "Blocked by Degrade Rule";
        }
    
        public String circuitBreakerRuleBlockHandler(BlockException ex) {
            return "Blocked by Circuit Breaker Rule";
        }
    }
    
    
    1. 在 Sentinel 控制台中配置不同类型的规则,如系统保护规则、流控规则、热点参数限流规则等。
    2. 使用 Postman 或其他工具对不同类型的规则进行测试,观察规则的生效情况。

    通过以上步骤,你可以理解和体验不同类型规则的优先级以及如何设置和配置它们。根据实际业务需求,你可以根据优先级的关系,适当调整规则的配置,确保 Sentinel 规则的正确生效,以达到稳定的微服务运行状态。

12. 总结和展望

  • Sentinel的局限性

    1. 性能开销: Sentinel 在进行流量控制和熔断降级时,会有一定的性能开销。需要权衡性能与稳定性之间的关系。
    2. 规则复杂性: 随着业务的增长,规则配置可能变得复杂。管理大规模规则可能会带来挑战。
    3. 规则动态性: Sentinel 的规则配置通常需要手动设置,不能实时地根据业务需求进行动态调
  • 未来发展方向

    1. 性能优化: 随着技术的发展,Sentinel 有望进一步优化性能,降低性能开销,提高系统的吞吐量。
    2. 规则自动化管理: 未来的版本可能会加强规则的自动化管理,例如动态规则的生成和调整,更加智能的配置。
    3. 更多的集成支持: Sentinel 可能会继续与更多的微服务框架进行集成,以满足不同用户的需求。
    4. 更强大的监控和分析功能: Sentinel 控制台 Dashboard 未来可能会增加更多的监控和分析功能,帮助用户更好地理解和优化微服务的运行状态。
                                    ⏳  名言警句:说会的,说对的
                                    ✨ 原创不易,还希望各位大佬支持一下
                                    👍 点赞,你的认可是我创作的动力!
                                    ⭐️ 收藏,你的青睐是我努力的方向!
                                    ✏️ 评论,你的意见是我进步的财富!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值