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

2023-10-27

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 未来可能会增加更多的监控和分析功能,帮助用户更好地理解和优化微服务的运行状态。
                                    ⏳  名言警句:说会的,说对的
                                    ✨ 原创不易,还希望各位大佬支持一下
                                    									
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringCloudAlibaba微服务架构搭建(五)Sentinel 详细教程(实战教程) 的相关文章

  • 8051单片机并行I/0口读写

    8051单片机并行I 0口读写 作者 佚名 文章来源 本站原创 点击数 338 更新时间 2011 08 10 前两天看资料 见到关于I O口作为输入时 要先输出1的说明 有点迷惑 今天特意查了一些资料 费了半天劲 虽然还没有完全弄明白 但
  • 服务器常用指令—重启tomcat

    重启Tomcat 关闭Tomcat 进入Tomcat下的bin目录 tomcat bin 使用Tomcat关闭命令 shutdown sh 查看Tomcat是否关闭成功 ps ef grep java 开启Tomcat startup sh
  • Contrastive Regression for Domain Adaptation on Gaze Estimation CVPR 2022 对比学习+目标域有样本无标注(伪标签)

    原文链接 补充材料 概括 本文将分类对比学习推广到回归 采用回归任务里真值的相似性代替分类任务里的类别标签一致性划分 在无标注的目标域采用伪标签进行训练 分类对比学习损失 s为特征的余弦相似性 损失函数L分子与正样本对特征相似程度和正相关
  • 如何在mac上安装多版本python并配置PATH

    摘要 mac 默认安装的python是 python3 但是如果我们需要其他python版本时 该怎么办呢 例如 需要python2 版本 如果使用homebrew安装会提示没有python2 同时使用python version 会发现c
  • linux中的ldd命令简介

    在linux中 有些命令是大家通用的 比如ls rm mv cp等等 这些我觉得没有必要再细说了 而有些命令 只有开发人员才会用到的 这类命令 作为程序员的我们 是有必要了解的 有的甚至需要熟练使用 有的人总说 这些命令不重要 用的时候去查
  • Elasticsearch基础学习笔记

    目录 一 全文搜索 1 数据分类 2 搜索分类 3 什么是全文搜索 全文检索是指 倒排索引 二 ElasticSearch简介 1 ElasticSearch是什么 2 ElasticSearch特点 3 ElasticSearch版本特性

随机推荐

  • C++学习(三三八)RSP文件

    RSP Response Text File 是一种资源文件 用编程软件或文本编辑工具可以打开 如VC Notepad等等 RSP 文件包含一个或多个命令行参数 由包含在 NET 编译器平台 也称为Roslyn 中的C 编译器 CSC 使用
  • dns服务器修改解析地址,dns服务器修改解析地址

    dns服务器修改解析地址 内容精选 换一换 obsutil是适用于Windows macOS和Linux操作系统的命令行工具 支持通过配置内网DNS服务器地址的方式 使在华为云上的Linux ECS通过内网直接访问OBS 下面将介绍其具体操
  • 内中断

    1 CPU根据中断码如何找到中断处理程序 要定位中断处理程序 就需要找到中断处理程序的段地址和偏移地址 如果根据中断码找到他们 这就引入中断向量表 CPU用8位的中断类型码通过中断向量表找到相应的中断处理程序的入口地址 2 使用中断类型码找
  • OpenCV实战(五)——对象简单计数

    现在我们用OpenCV来计数图像当中的目标物体数目 针对各个物体之间没有粘连的情况 include
  • 离散数学 --- 谓词逻辑 --- 谓词合式公式推理

    第一部分 推理形式和推理规则 1 谓词在拥有命题演算的基本蕴含公式的同时 还有着自己独有的基本蕴含公式 当我们的描述在个体和整体之间转换时 就需要进行量词的消去和添加 1 全称特指规则 US规则 其实就是全称量词消去规则 2 全称量词消去有
  • docker-compose

    能做什么 一个用来把 docker 自动化的东西 有了 docker compose 你可以把所有繁复的 docker 操作全都一条命令 自动化的完成 通过创建compose文件 YUML语法 在这个文件上面描述应用的架构 如使用什么镜像
  • 《零基础入门学习Python》(6)--Python之常用操作符

    前言 Python当中常用操作符 有分为以下几类 幂运算 正负号 算术操作符 比较操作符 lt lt gt gt 逻辑运算符 not and or 操作符介绍 幂运算 gt gt gt 3 3 27 正负号 幂运算的优先级比较特殊 因为幂操
  • 凸多边形面积_C++计算任意多边形的面积

    任意多边形的面积计算 拾忆楓灵的博客 CSDN博客 blog csdn net 计算任意多边形的面积 tenos 博客园 www cnblogs com 完美解决计算3D空间任意多边形面积 Studiouss的博客 CSDN博客 blog
  • 微信小程序开发实战 ②〇(Npm包)

    作者 SYFStrive 作者 SYFStrive 博客首页 HomePage 微信小程序 个人社区 欢迎大佬们加入 社区链接 觉得文章不错可以点点关注 专栏连接 感谢支持 学累了可以先看小段由小胖给大家带来的街舞 微信小程序 目录 什么是
  • React 性能优化完全指南,将自己这几年的心血总结成篇!

    作者 MoonBall 原文地址 https juejin cn post 6935584878071119885 本文分为三部分 首先介绍 React 的工作流 让读者对 React 组件更新流程有宏观的认识 然后列出笔者总结的一系列优化
  • MUMPS 安装

    Centos 7 Install MUMPS 1 下载安装包 需要提交申请 http mumps enseeiht fr 2 安装并行版MUMPS需要以下一些依赖包 MPI BLAS library BLACS library ScaLAP
  • C语言种根号怎么表示 比如(1-x)的二分之一次方

    库函数sqrt x include
  • 5.39 综合案例2.0 - STM32蓝牙遥控小车3(摇杆控制)

    综合案例2 0 蓝牙遥控小车1 摇杆控制 成品展示 案例说明 器件说明 小车连线 小车源码 PS2摇杆手柄 遥控连线 摇杆代码 成品展示 用python开发板和stm32制作一个摇杆控制蓝牙全向智能车 源码开放 案例说明 用STM32单片机
  • 《计算机网络》期末模拟考试练习+答案

    期末考试模拟试题参考 一 单选题 共20题 20分 1 下列有线传输介质中抗电磁干扰最好的是 A 屏蔽双绞线 B 同轴电缆 C 非屏蔽双绞线 D 光纤 正确答案 D 解析 2 TELNET通过TCP IP协议在客户机和远程登录服务器之间建立
  • struct和typedef struct的用法解析

    1 首先 注意在C和C 里不同 在C中定义一个结构体类型要用typedef typedef struct Student int a Stu 于是在声明变量的时候就可 Stu stu1 如果没有typedef就必须用struct Stude
  • Calendar对象获取当前周的bug

    项目场景 双周项目管理 需要获取当前周为一年之中的第几周 原先的代码是用Calendar对象 先用setTime 把当前时间传入 再用get 3 获取一年中的第几周 问题描述 实际发现会比真实的周少一点 且时间是周日到周六为一周 原因分析
  • python:pyqt5的基本使用

    文章目录 基本框架 程序启动画面 一 设置主界面 1 窗体字体设置 2 界面设置 二 设置控件 1 QMessageBox消息框 2 文本编辑框和文本浏览框 3 各种按钮 4 标签 5 单行文本框 6 下拉选择框和数字调节框 7 滑动条和旋
  • 简单快速实现子序列的判断

    针对力扣的判断子序列题目进行算法实现 原题链接可以点击地址 https leetcode cn com problems is subsequence 基于近两年较火的力扣leetcode刷题训练站点 本人为了能够保持算法和数据结构这些底层
  • CVPR 2021 目标检测论文大盘点(65篇论文)

    前言 一共搜集了65篇2D目标检测论文 涉及 通用目标检测 旋转目标检测 Few shot 自监督 半监督 无监督目标检测等方向 作者 Amusi 来源 CVer CVer 正式盘点CVPR 2021上各个方向的工作 本篇是热度依然很高的2
  • SpringCloudAlibaba微服务架构搭建(五)Sentinel 详细教程(实战教程)

    SpringCloudAlibaba微服务架构搭建 五 Sentinel 详细教程 实战教程 1 介绍 1 1 什么是Spring Cloud Alibaba Sentinel Spring Cloud Alibaba Sentinel 简
Powered by Hwhale