SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)

文章目录

  • 十九、SpringCloud Alibaba Sentinel实现熔断与限流
    • 简介
      • 下载
        • docker
    • 初始化演示工程
    • 流控规则
        • 阈值类型
          • QPS与线程数的区别
        • 流控模式
          • 直接
          • 关联
          • 链路
        • 流控效果
          • 快速失败
          • 预热(Warm Up)
          • 排队等待
    • 降级规则
      • 降级策略实战
        • RT
        • 异常比例
        • 异常数
    • 热点key限流
        • 参数例外项
    • 系统规则
    • @SentinelResource
      • 按资源名称限流+后续处理
      • 按照URL地址限流+后续处理
      • 上面兜底方案面临的问题
      • 客户自定义限流处理逻辑
      • 更多注解属性说明
    • 服务熔断功能
      • Ribbon系列
        • 新建提供者
        • 新建消费者
        • 只配置fallback
        • 只配置blockHandler
        • 配置fallback和blockHandler
        • 忽略属性
      • Feign系列
    • 熔断限流框架对比
    • 规则持久化

十九、SpringCloud Alibaba Sentinel实现熔断与限流

简介

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第1张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第2张图片
官网:https://github.com/alibaba/sentinel
中文版:https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第3张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第4张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第5张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第6张图片
文档:https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-alibaba.html#_spring_cloud_alibaba_sentinel
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第7张图片

下载

下载:https://github.com/alibaba/Sentinel/releases
本来想着只有一个jar包,就不使用docker了,直接下载到本地运行,但是是真的下不动,点下载转了半天没反应,真的是服了。

docker

#拉取sentinel镜像
docker pull bladex/sentinel-dashboard

#运行sentinel(docker里的sentinel是8858端口)
docker run --name sentinel -d -p 8858:8858 bladex/sentinel-dashboard

#把nacos和mysql也启动起来

在浏览器输入:http://10.211.55.26:8858/#/login(因为linux出了点问题,重装了,所以ip也变了)
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第8张图片
账号和密码都是sentinel
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第9张图片

控制台使用说明:https://github.com/alibaba/Sentinel/wiki/%E6%8E%A7%E5%88%B6%E5%8F%B0

初始化演示工程

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第10张图片

  1. 新建模块cloudalibaba-sentinel-service8401

  2. pom

    <dependencies>
        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibaba.cspgroupId>
            <artifactId>sentinel-datasource-nacosartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
    
  3. yml

    server:
      port: 8401
    
    spring:
      application:
        name: cloudalibaba-sentinal-service
      cloud:
        nacos:
          discovery:
            #Nacos服务注册中心地址(改成自己的服务器ip地址,本地用localhost‍)
            server-addr: 10.211.55.26:8848
        sentinel:
          transport:
            #配置Sentin dashboard地址(改成自己的服务器ip地址,本地用localhost‍)
            dashboard: 10.211.55.26:8858
            # 默认8719端口,假如被占用了会自动从8719端口+1进行扫描,直到找到未被占用的 端口
            port: 8719
            
    
    management:
      endpoints:
        web:
          exposure:
            include: '*'
    
  4. 主启动类

    @EnableDiscoveryClient
    @SpringBootApplication
    public class MainApp8401 {
    
        public static void main(String[] args) {
            SpringApplication.run(MainApp8401.class, args);
        }
    }
    
  5. controller

    @RestController
    public class FlowLimitController {
    
        @GetMapping("/testA")
        public String testA() {
            return "----testA";
        }
    
        @GetMapping("/testB")
        public String testB() {
            return "----testB";
        }
    
    }
    
  6. 测试,启动8401,然后刷新sentinel后台页面(因为sentinel采用懒加载策略,所以需要调用服务后才在后台显示)
    在浏览器分别输入,然后刷新sentinel后台页面:
    http://localhost:8401/testA
    http://localhost:8401/testB
    SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第11张图片

流控规则

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第12张图片
流量控制
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第13张图片
可在流控规则处新建:
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第14张图片
也可簇点链路处指定添加:
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第15张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第16张图片
每秒请求数超过1个就会限流。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第17张图片

阈值类型

QPS与线程数的区别

在这里插入图片描述
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第18张图片
QPS是直接挡在外面,而线程数是有多少个线程在处理,放进来后,有线程是空闲状态就对请求进行处理,都没空闲,就限流(关门打狗)。

流控模式

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第19张图片

直接

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第20张图片

关联

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第21张图片
A去调用B,B如果资源不足了,就限流A。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第22张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第23张图片
此时不管调用多少次A都不会限流,而此时超过1秒调用1次B,则会限流A。

使用Postman进行多次访问。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第24张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第25张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第26张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第27张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第28张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第29张图片

链路

在网上搜关于链路的是用下面这个例子,然而显示不了限流的效果。

新建一个TestService

@Service
public class TestService {

    @SentinelResource("getTest")
    public void getTest(){
    System.out.println("getTest...");
    }

}

然后在FlowLimitController添加修改:

    @Resource
    TestService testService;
    
    @GetMapping("/testA")
    public String testA() {
        testService.getTest();
        return "----testA";
    }

    @GetMapping("/testB")
    public String testB() {
        testService.getTest();
        return "----testB";
    }

然后重新启动8401,输入http://localhost:8401/testAhttp://localhost:8401/testB
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第30张图片
给getTest添加流控链路规则。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第31张图片

流控效果

流控效果只有QPS有,线程数没有。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第32张图片

快速失败

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第33张图片

预热(Warm Up)

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第34张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第35张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第36张图片
在这里插入图片描述
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第37张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第38张图片
对testA新增流控规则
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第39张图片
然后输入http://localhost:8401/testA,不停刷新,前5秒会限流,5秒后只要每秒不超过10个请求,就不会限流。

排队等待

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第40张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第41张图片
在这里插入图片描述
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第42张图片
在testB方法中添加

        log.info(Thread.currentThread().getName() + "\t ...testB");

然后重启8401
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第43张图片

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第44张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第45张图片
postman发起的每秒10个请求进行排队,testB每秒处理一个请求。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第46张图片

降级规则

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第47张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第48张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第49张图片
在这里插入图片描述
在这里插入图片描述
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第50张图片

降级策略实战

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第51张图片

RT

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第52张图片
在这里插入图片描述
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第53张图片

在FlowLimitController中添加

    @GetMapping("/testD")
    public String testD() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("testD 测试RT");
        return "----testD";
    }

启动8401,在浏览器输入http://localhost:8401/testD,然后在sentinel设置testD降级规则。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第54张图片
请求处理完成的时间为200毫秒(阈值),超过这个时间熔断降级进入时间窗口期不处理请求,1秒后退出时间窗口期,继续处理请求。(前提是一秒请求数超过5个,如果请求数没超过5个,就算请求处理的时间超过阈值也不会熔断降级)

然后用Jmeter进行压力测试。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第55张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第56张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第57张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第58张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第59张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第60张图片

异常比例

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第61张图片
在这里插入图片描述
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第62张图片

修改testD

    @GetMapping("/testD")
    public String testD() {
        log.info("testD 异常比例");
        int age = 10 / 0;   //百分百出错

        return "----testD";
    }

启动8401,浏览器输入http://localhost:8401/testD,然后在后台设置testD的降级规则。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第63张图片
处理请求出错超过0.2(20%,阈值),熔断降级,进入时间窗口期不处理请求,3秒后退出时间窗口期继续处理请求。(前提也是每秒请求数超过5个,防止不会熔断降级)

用Jmeter进行测试
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第64张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第65张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第66张图片

异常数

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第67张图片
在这里插入图片描述
因为是按照一分钟内的异常数对阈值进行比较,如果时间窗口小于60秒,可能会再次进入熔断状态。所以时间窗口一定要大于等于60秒。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第68张图片

在FlowLimitController里添加:

    @GetMapping("/testE")
    public String testE() {
        log.info("testE 测试异常数");
        int age = 10 / 0;
        return "----testE 测试异常数";
    }

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第69张图片
启动8401,浏览器输入http://localhost:8401/testE,然后在后台设置testE的降级规则。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第70张图片
一分钟内,如果访问处理出现异常的次数超过5次,熔断降级,进入时间窗口期不处理请求,61秒后退出时间窗口期继续处理请求。(时间窗口必须大于等于60秒,防止再次熔断降级)

刷新6次,http://localhost:8401/testE
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第71张图片

热点key限流

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第72张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第73张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第74张图片

在FlowLimitController中添加:

    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey", blockHandler = "deal_testHotKey")
    public String testHotKey(@RequestParam(value = "p1", required = false)String p1,
                             @RequestParam(value = "p2", required = false)String p2) {
        return "----testHotKey";
    }
    
    //兜底方法
    public String deal_testHotKey(String p1, String p2, BlockException exception) {
        // sentinel的默认提示都是: Blocked by Sentinel (flow limiting)
        return "----deal_testHotKey, o(╥﹏╥)o";
    }

重启8401,浏览器输入http://localhost:8401/testHotKey,然后在后台对testHotKey进行热点规则配置。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第75张图片
如果每秒的访问请求带有索引为0的参数的数量超过1,进入统计窗口期,然后调用兜底方法,1秒后退出统计窗口期,继续处理请求。

http://localhost:8401/testHotKey?p1=1
http://localhost:8401/testHotKey?p1=1&p2=2
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第76张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第77张图片

如果设置热点规则,而@SentinelResource注解里没有指明blockHandler兜底方法,就会把直接把错误页面信息打印到前台。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第78张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第79张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第80张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第81张图片

参数例外项

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第82张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第83张图片
高级选项只有在热点规则里有,簇点链路无法配置高级选项。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第84张图片
http://localhost:8401/testHotKey?p1=1
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第85张图片
http://localhost:8401/testHotKey?p1=vip
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第86张图片

给testHotKey方法添加int i = 1 / 0;异常。
然后重新测试,发现兜底方法不适用于异常,有异常会直接打印到页面。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第87张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第88张图片

系统规则

Sentinel 系统自适应限流从整体维度对应用入口流量进行控制,结合应用的 Load、CPU 使用率、总体平均 RT、入口 QPS 和并发线程数等几个维度的监控指标,通过自适应的流控策略,让系统的入口流量和系统的负载达到一个平衡,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第89张图片

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第90张图片
针对整个系统的,每秒访问量超过1(阈值),限流。

http://localhost:8401/testA
在这里插入图片描述
http://localhost:8401/testB
在这里插入图片描述

@SentinelResource

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第91张图片

按资源名称限流+后续处理

资源名称
在这里插入图片描述
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第92张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第93张图片
在pom添加

 
 
 <dependency>
     <groupId>com.angenin.springcloudgroupId>
     <artifactId>cloud-api-commonsartifactId>
     <version>${project.version}version>
 dependency>

新建RateLimitController:

@RestController
public class RateLimitController {

    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "handleException")
    public CommonResult byResource() {
        return  new CommonResult(200,"按照资源名称限流测试",new Payment(2020L,"serial001"));
    }

	//兜底方法
    public CommonResult handleException(BlockException exception) {
        return  new CommonResult(444,exception.getClass().getCanonicalName() + "\t 服务不可用");
    }
}

启动8401
http://localhost:8401/byResource
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第94张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第95张图片
用资源名称进行配置兜底方法才生效。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第96张图片
多次刷新页面
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第97张图片
在这里插入图片描述
在这里插入图片描述

按照URL地址限流+后续处理

URL地址:
在这里插入图片描述
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第98张图片
在RateLimitController中添加:

    @GetMapping("/rateLimit/byUrl")
    @SentinelResource(value = "byUrl")	//没有兜底方法,系统就用默认的
    public CommonResult byUrl() {
        return  new CommonResult(200,"按照byUrl限流测试",new Payment(2020L,"serial002"));
    }

启动8401
http://localhost:8401/rateLimit/byUrl
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第99张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第100张图片
多次刷新:
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第101张图片

上面兜底方案面临的问题

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第102张图片

客户自定义限流处理逻辑

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第103张图片
新建myhandler.CustomerBlockHandler自定义限流处理类:

public class CustomerBlockHandler {

    public static CommonResult handlerException(BlockException exception) {
        return  new CommonResult(444,"按照客户自定义限流测试,Glogal handlerException ---- 1");
    }

    public static CommonResult handlerException2(BlockException exception) {
        return  new CommonResult(444,"按照客户自定义限流测试,Glogal handlerException ---- 2");
    }
}

在RateLimitController中添加:

    //CustomerBlockHandler
    @GetMapping("/rateLimit/customerBlockHandler")
    @SentinelResource(value = "customerBlockHandler",
            blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handlerException2")
    public CommonResult customerBlockHandler() {
        return  new CommonResult(200,"按照客户自定义限流测试",new Payment(2020L,"serial003"));
    }

启动8401
http://localhost:8401/rateLimit/customerBlockHandler
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第104张图片
用资源名称进行配置兜底方法才生效。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第105张图片
多次刷新:
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第106张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第107张图片

更多注解属性说明

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第108张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第109张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第110张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第111张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第112张图片

服务熔断功能

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第113张图片

Ribbon系列

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第114张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第115张图片

新建提供者

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第116张图片

  1. 新建模块cloudalibaba-provider-payment9003

  2. pom

    <dependencies>
        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>
        
        <dependency>
            <groupId>com.angenin.springcloudgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>${project.version}version>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
    
  3. yml

    server:
      port: 9003
    
    spring:
      application:
        name: nacos-payment-provider
      cloud:
        nacos:
          discovery:
            server-addr: 10.211.55.26:8848  #nacos
    
    management:
      endpoints:
        web:
          exposure:
            include: '*'
    
  4. 主启动类

    @SpringBootApplication
    @EnableDiscoveryClient
    public class PaymentMain9003 {
    
        public static void main(String[] args) {
            SpringApplication.run(PaymentMain9003.class,args);
        }
    }
    
  5. controller

    @RestController
    public class PaymentController {
    
        @Value("${server.port}")    //spring的注解
        private  String serverPort;
    
        public static HashMap<Long, Payment> map = new HashMap<>();
        static {
            map.put(1L,new Payment(1L,"1111"));
            map.put(2L,new Payment(2L,"2222"));
            map.put(3L,new Payment(3L,"3333"));
        }
    
    
        @GetMapping(value = "/paymentSQL/{id}")
        public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
            Payment payment = map.get(id);
            CommonResult<Payment> result = new CommonResult<>(200,"from mysql,serverPort: " + serverPort,payment);
            return result;
        }
    }
    
  6. 按照9003新建9004

新建消费者

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第117张图片

  1. 新建模块cloudalibaba-consumer-nacos-order84

  2. pom

    <dependencies>
        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discoveryartifactId>
        dependency>
        
        <dependency>
            <groupId>com.alibaba.cloudgroupId>
            <artifactId>spring-cloud-starter-alibaba-sentinelartifactId>
        dependency>
        
        <dependency>
            <groupId>com.angenin.springcloudgroupId>
            <artifactId>cloud-api-commonsartifactId>
            <version>${project.version}version>
        dependency>
        <dependency>
            <groupId>org.springframework.cloudgroupId>
            <artifactId>spring-cloud-starter-openfeignartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
    
  3. yml

    server:
      port: 84
    
    spring:
      application:
        name: nacos-order-consumer
      cloud:
        nacos:
          discovery:
            server-addr: 10.211.55.26:8848  #nacos
        sentinel:
          transport:
            dashboard: 10.211.55.26:8858    #sentinel
            port: 8719
    
    #消费者将去访问的微服务名称
    server-url:
      nacos-user-service: http://nacos-payment-provider
    
    #激活Sentinel对Feign的支持
    feign:
      sentinel:
        enabled: true
    
  4. 主启动类

    @EnableDiscoveryClient
    @SpringBootApplication
    @EnableFeignClients
    public class OrderMain84 {
    
        public static void main(String[] args) {
            SpringApplication.run(OrderMain84.class,args);
        }
    }
    
  5. config

    @Configuration
    public class ApplicationContextConfig {
    
        @Bean
        @LoadBalanced
        public RestTemplate getRestTemplate() {
            return new RestTemplate();
        }
    }
    
  6. controller

    @RestController
    @Slf4j
    public class CircleBreakerController {
    
        public static  final  String SERVICE_URL = "http://nacos-payment-provider";
    
        @Resource
        private RestTemplate restTemplate;
    
        @RequestMapping("/consumer/fallback/{id}")
        @SentinelResource(value = "fallback")   //没有配置
        public CommonResult<Payment> fallback(@PathVariable Long id) {
            CommonResult<Payment> result = restTemplate.getForObject(
                    SERVICE_URL + "/paymentSQL/" + id,CommonResult.class,id);
    
            if(id == 4){
                throw new IllegalArgumentException("IllegalArgument,非法参数异常...");
            }else if(result.getData() == null) {
                throw new NullPointerException("NullPointerException,该ID没有对应记录,空指针异常");
            }
    
            return  result;
        }
        
    }
    

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第118张图片
在这里插入图片描述
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第119张图片
启动9003,9004,84
http://localhost:84/consumer/fallback/1
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第120张图片
在这里插入图片描述

http://localhost:84/consumer/fallback/4
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第121张图片
http://localhost:84/consumer/fallback/5
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第122张图片

只配置fallback

修改84的CircleBreakerController类的fallback方法中的@SentinelResource注解,并在类中添加

    @SentinelResource(value = "fallback",fallback ="handlerFallback")   //只配置fallback(只负责业务异常)


    //fallback兜底
    public CommonResult handlerFallback(@PathVariable Long id,Throwable e) {
        Payment payment = new Payment(id,"null");
        return new CommonResult(444,"异常handlerFallback,exception内容: " + e.getMessage(), payment);
    }

重新运行
http://localhost:84/consumer/fallback/4
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第123张图片
http://localhost:84/consumer/fallback/5
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第124张图片

只配置blockHandler

修改@SentinelResource注解,并在类中添加

    @SentinelResource(value = "fallback", blockHandler = "blockHandler")	//只配置blockHandler(只负责sentinel控制台配置违规)


    //blockHandler兜底
    public CommonResult blockHandler(@PathVariable Long id,BlockException e) {
        Payment payment = new Payment(id,"null");
        return new CommonResult(444,"blockHandler-sentinel 限流,BlockException: " + e.getMessage(), payment);
    }

重启项目
访问http://localhost:84/consumer/fallback/1,然后在sentinel后台进行配置。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第125张图片
http://localhost:84/consumer/fallback/5
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第126张图片
因为没配置指定fallback兜底方法,所以会直接显示错误页面,配置了blockHandler兜底方法,所以当sentinel配置违规会执行blockHandler兜底方法。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第127张图片

配置fallback和blockHandler

修改@SentinelResource注解

    @SentinelResource(value = "fallback", fallback ="handlerFallback", blockHandler = "blockHandler")

重启项目,输入http://localhost:84/consumer/fallback/1,然后到后台配置。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第128张图片
http://localhost:84/consumer/fallback/1多次刷新执行blockHandler兜底方法。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第129张图片
http://localhost:84/consumer/fallback/5执行fallback兜底方法。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第130张图片
http://localhost:84/consumer/fallback/5多次刷新执行blockHandler兜底方法。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第131张图片
当@SentinelResource注解fallback和blockHandler都指定后,然后同时符合,优先执行blockHandler兜底方法。

忽略属性


修改@SentinelResource注解:

    @SentinelResource(value = "fallback", 
            fallback ="handlerFallback", 
            blockHandler = "blockHandler", 
            exceptionsToIgnore = {IllegalArgumentException.class})
    //如果出现exceptionsToIgnore中的异常,不运行fallback兜底方法。

http://localhost:84/consumer/fallback/4
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第132张图片
http://localhost:84/consumer/fallback/5
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第133张图片

Feign系列

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第134张图片
修改84

  1. pom

    
    <dependency>
        <groupId>org.springframework.cloudgroupId>
        <artifactId>spring-cloud-starter-openfeignartifactId>
    dependency>
    
  2. yml

    #前面也已经添加了
    #激活Sentinel对Feign的支持
    feign:
      sentinel:
        enabled: true
    
  3. 主启动类上添加@EnableFeignClients(也已经添加了)

  4. service
    PaymentService接口

    @FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
    public interface PaymentService {
    
        @GetMapping(value = "/paymentSQL/{id}")
        public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
    
    }
    

    PaymentFallbackService实现类

    @Component
    public class PaymentFallbackService implements PaymentService{
        
        @Override
        public CommonResult<Payment> paymentSQL(Long id) {
            return new CommonResult<>(444,"服务降级返回,---PaymentFallbackService",new Payment(id,"ErrorSerial"));
        }
    }
    
  5. controller
    CircleBreakerController中添加:

        //======= OpenFeign
        @Resource
        private PaymentService paymentService;
    
        @GetMapping(value = "/consumer/paymentSQL/{id}")
        public CommonResult< Payment > paymentSQL(@PathVariable("id") Long id){
            return paymentService.paymentSQL(id);
        }
    

启动项目,http://localhost:84/consumer/paymentSQL/1
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第135张图片
关闭9003和9004,执行@FeignClient的fallback兜底方法PaymentFallbackService。
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第136张图片

熔断限流框架对比

SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第137张图片
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第138张图片

规则持久化

在这里插入图片描述
在这里插入图片描述
SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第139张图片
修改8401

  1. pom

    	
        
        <dependency>
            <groupId>com.alibaba.cspgroupId>
            <artifactId>sentinel-datasource-nacosartifactId>
        dependency>
    
  2. yml

    	      datasource:
    	        ds1:
    	          nacos:
    	            server-addr: 10.211.55.26:8848  #nacos
            		dataId: ${spring.application.name}
    	            groupId: DEFAULT_GROUP
    	            data-type: json
    	            rule-type: flow
    
    feign:
      sentinel:
        enabled: true #激活Sentinel 对Feign的支持
    

    SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第140张图片

  3. 在nacos后台添加配置:
    SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第141张图片

    [
        {
            "resource": "/rateLimit/byUrl",
            "limitApp": "default",
            "grade": 1,
            "count": 1,
            "strategy": 0,
            "controlBehavior": 0,
            "clusterMode": false
        }
    ]	
    

    SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第142张图片
    SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第143张图片
    启动8401
    http://localhost:8401/rateLimit/byUrl多次刷新
    SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第144张图片
    SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第145张图片
    停止8401
    SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第146张图片
    再次启动8401,因为sentinel是懒加载模式,所以需要先访问http://localhost:8401/rateLimit/byUrl,然后查看sentinel后台。
    SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第147张图片
    多次刷新http://localhost:8401/rateLimit/byUrl
    SpringCloud入门学习笔记(19高级部分,熔断与限流【Sentinel】)_第148张图片
    实现sentinel配置的持久化。

下一篇笔记:SpringCloud入门学习笔记(20高级部分,处理分布式事务【Seata】)

学习视频(p111-p137):https://www.bilibili.com/video/BV18E411x7eT?p=111

你可能感兴趣的:(SpringCloud)