SpringCloud

代码链接
https://github.com/lidonglin-bit/cloud

一、Sentinel介绍

1.官网

https://github.com/alibaba/Sentinel
中文
https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D

2.是什么

一句话解释之前的Hystrix
在这里插入图片描述
在这里插入图片描述

3.能干嘛

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4.去哪下

https://github.com/alibaba/Sentinel/releases

5.怎么玩

https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-alibaba.html#_spring_cloud_alibaba_sentinel
在这里插入图片描述

  • 服务使用中的各种问题
    • 服务雪崩
    • 服务降级
    • 服务熔断
    • 服务限流

二、安装Sentinel控制台

1.sentinel组件由2部分组成

Sentinel 分为两个部分:
核心库Java 客户端不依赖任何框架/库能够运行于所有 Java 运行时环境同时对 Dubbo / Spring Cloud 等框架也有较好的支持。

控制台Dashboard基于 Spring Boot 开发打包后可以直接运行不需要额外的 Tomcat 等应用容器。

  • 后台
  • 前台8080

2.安装步骤

1.下载
https://github.com/alibaba/Sentinel/releases
下载到本地sentinel-dashboard-1.7.0.jar
2.运行命令
前提
java8环境OK
8080端口不能被占用
命令

java -jar sentinel-dashboard-1.7.0.jar 

3.访问sentinel管理界面
http://localhost:8080
登录账号密码均为sentinel

三、初始化演示工程

1.启动Nacos8848成功

http://localhost:8848/nacos/#/login

2.案例

1.创建Modulecloudalibaba-sentinel-service8401
2.POM

    <dependencies>
        <dependency>
            <groupId>com.donglin.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>4.6.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

3.YML

server:
  port: 8401

spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719  #默认8719应用与Sentinel控制台交互的端口应用本地会起一个该端口占用HttpServer

management:
  endpoints:
    web:
      exposure:
        include: '*'

在这里插入图片描述
https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#production-ready-endpoints

4.主启动

package com.donglin.springcloud.alibaba;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

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

5.业务类FlowLimitController

package com.donglin.springcloud.alibaba.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class FlowLimitController{
    @GetMapping("/testA")
    public String testA() {
        return "------testA";
    }

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

3.启动Sentinel8080

java -jar sentinel-dashboard-1.7.0.jar

4.启动微服务8401

5.启动8401微服务后查看sentienl控制台

空空如也啥都没有
Sentinel采用的懒加载说明
执行一次访问即可
http://localhost:8401/testA
http://localhost:8401/testB
效果
在这里插入图片描述

结论
sentinel8080正在监控微服务8401

四、流控规则

1.基本介绍

在这里插入图片描述

进一步解释说明

在这里插入图片描述

2.流控模式

2.1 直接默认

  • 直接->快速失败

  • 系统默认

  • 测试QPS

  • 配置及说明

  • 表示1秒钟内查询1次就是OK,若超过次数1就直接-快速失败报默认错误
    在这里插入图片描述

  • 快速点击访问 http://lcalhost:8401/testA

  • 结果

  • Blcked by Sentinel (flw limiting)
    在这里插入图片描述

  • 测试线程数
    在这里插入图片描述

  • 快速点击访问 http://localhost:8401/testA

  • 结果

  • 不会出现http://localhost:8401/testA线程处理请求很快
    在这里插入图片描述

但是在映射方法里添加sleep后同样也会出现Blocked by Sentinel (flow limiting)默认提示信息。

  • 思考
    • 直接调用默认报错信息技术方面OK but是否应该有我们自己的后续处理
    • 类似有一个fallback的兜底方法

2.2 关联

  • 是什么
    • 当关联的资源达到阈值时就限流自己
    • 当与A关联的资源B达到阈值后就限流自己
    • B惹事A挂了

2.3 配置A

  • 设置效果
  • 当关联资源/testB的QPS阀值超过1时就限流/testA的REST访问地址当关联资源到阀值后闲置配置的的资源名。
    在这里插入图片描述

2.4 postman模拟并发密集访问testB

  • 访问testB成功
    在这里插入图片描述

  • postman里新建多线程集合组将请求保存到集合组
    在这里插入图片描述

  • 运行线程集合组
    在这里插入图片描述

  • 设置并发访问参数
    在这里插入图片描述

  • Run

    • 大批量线程高并发访问B导致A失效了
  • 运行后发现testA挂了

  • 点击访问http://localhost:8401/testA

  • 结果

    • Blocked by Sentinel (flow limiting)

2.5 链路

  • 多个请求调用了同一个微服务
  • 家庭作业试试

3.流控效果

3.1 直接->快速失败默认的流控处理

  • 直接失败抛出异常Blocked by Sentinel (fl- w limiting)
  • 源码com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController

3.2 预热

在这里插入图片描述

在这里插入图片描述

  • 限流 冷启动
    https://github.c- m/alibaba/Sentinel/wiki/%E9%99%90%E6%B5%81—%E5%86%B7%E5%90%AF%E5%8A%A8

  • 源码

    • com.alibaba.csp.sentinel.slots.block.flow.controller.WarmUpController
      在这里插入图片描述
  • Warmup配置
    默认 coldFactor 为 3即请求 QPS 从 threshold / 3 开始经预热时长逐渐升至设定的 QPS 阈值。

  • 案例阈值为10 + 预热时长设置5秒。

  • 系统初始化的阈值为10/3约等于3即阈值刚开始为3然后过了5秒后阈值才慢慢升高恢复到10
    在这里插入图片描述

  • 多次点击http://localhost:8401/testB

  • 刚开始不行后续慢慢OK

  • 应用场景

    • 如秒杀系统在开启的瞬间会有很多流量上来很有可能把系统打死预热方式就是为了保护系统可慢慢的把流量放进来慢慢的把阈值增长到设置的阈值。

3.3 排队等待

  • 匀速排队让请求以均匀的速度通过阈值类型必须设置成QPS否则无效。

  • 设置含义/testB每秒1次请求超过的话就排队等待等待的超时时间为20000毫秒。
    在这里插入图片描述

  • 官网
    在这里插入图片描述

  • 源码 com.alibaba.csp.sentinel.slots.block.flow.controller.RateLimiterController

  • 测试

    • 增加打印语句
@GetMapping("/testB")
public String testB() {
log.info(Thread.currentThread().getName()+"\t ...testB");
return "------testB";
}
  • 增加线程组直接10个线程并发排队被依次处理
    在这里插入图片描述

五、降级规则

1.官网

[https://github.c- m/alibaba/Sentinel/wiki/%E7%86%94%E6%96%AD%E9%99%8D%E7%BA%A7](https://github.c- m/alibaba/Sentinel/wiki/%E7%86%94%E6%96%AD%E9%99%8D%E7%BA%A7)
在这里插入图片描述

2.基本介绍

  • 整体介绍
    在这里插入图片描述

  • RT(平均响应时间,秒级)

    • 平均响应时间 (DEGRADE_GRADE_RT)超过阈值 且 时间窗口内的请求>=5两个条件同时满足后触发降级窗口期过后关闭断路器
    • RT 最大4900 ms更大的需要通过启动配置项
      -Dcsp.sentinel.statistic.max.rt=xxx 来配置。
  • 异常比例秒级

    • QPS>=5且异常比例秒级统计超过阈值时触发降级时间窗口结束后关闭降级
    • 异常数分钟级
    • 异常数分钟统计超过阈值时触发降级时间窗口结束后关闭降级
  • 进一步说明

    • Sentinel熔断降级会在调用链路中某个资源出现不稳定状态时例如调用超时或异常比例升高对这个资源的调用进行限制让请求快速失败避免影响到其他的资源而导致级联错误。
    • 当资源被降级后在接下来的降级时间窗口之内对该资源的调用都自动熔断默认行为是抛出DegradeExcepti- n。
  • Sentinel的断路器是没有半开状态的

    • 半开的状态系统自动去检测是否请求有异常没有异常就关闭断路器恢复使用有异常则继续打开断路器不可用。具体可以参考Hystrix
    • 复习Hystrix
      在这里插入图片描述

3.降级策略实战

3.1 RT

  • 是什么
    在这里插入图片描述

在这里插入图片描述

  • 测试
  • 代码
@GetMapping("/testD")
public String testD(){
        try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
        log.info("testD 测试RT");
        return "------testD";
}
  • 配置
    在这里插入图片描述

  • jmeter压测
    在这里插入图片描述

在这里插入图片描述

  • 结论
    永远一秒钟打进来10个线程大于5个了调用testD我们希望200毫秒处理完本次任务
    如果超过200毫秒还没处理完在未来1秒钟的时间窗口内断路器打开保险丝跳闸微服务不可用保险丝跳闸断电了
    后续停止jmeter,没有这么大的访问量了断路器关闭保险丝恢复微服务恢复OK

3.2 异常比例

  • 是什么
    在这里插入图片描述
    在这里插入图片描述

  • 测试

  • 代码

@GetMapping("/testD")
public String testD() {
        log.info("testD 测试异常比例");
        int age = 10/0;
        return "------testD";
}
  • 配置
    在这里插入图片描述

  • jmeter
    在这里插入图片描述

  • 演示
    在这里插入图片描述
    在这里插入图片描述

  • 结论

    • 按照上述配置
    • 单独访问一次必然来一次报错一次int age=10/0;,调一次错一次
      在这里插入图片描述
  • 开启jmeter后直接高并发送请求多次调用达到我们的配置条件了。

  • 断路器开启保险丝跳闸微服务不可用了不再报错error而是服务降级了。

3.3 异常数

  • 是什么
    在这里插入图片描述

时间窗口一定要大于等于60秒。
在这里插入图片描述

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

    • http://localhost:8401/testE
    • 第一次访问绝对报错因为除数不能为零我们看到error窗口但是达到5次报错后进入熔断后降级。
      在这里插入图片描述
  • 手动连续点5次后进入降级

六、热点key限流

1.基本介绍

  • 是什么
    在这里插入图片描述

2.官网

https://github.com/alibaba/Sentinel/wiki/热点参数限流

在这里插入图片描述

3.承上启下复习

  • 兜底方法
  • 分为系统默认和客户自定义两种
    • 之前的case限流出问题后都是用sentinel系统默认的提示 Blocked by Sentinel(flow limiting)
    • 我们能不能自定义类似hystrix,某个方法出现问题了就找对应的兜底降级方法
    • 结论
      从@HystrixCommand到@SentinelResource

4.代码

@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) {
    //int age = 10/0;
    return "------testHotKey";
}

//兜底方法
public String deal_testHotKey (String p1, String p2, BlockException exception){
    return "------deal_testHotKey,o(╥﹏╥)o";  
}

com.alibaba.csp.sentinel.slots.block.BlockException

5.配置

  • 配置
    在这里插入图片描述

在这里插入图片描述

  • 默认
    • @SentinelResource(value = “testHotKey”)
    • 异常打到了前台用户界面不友好

在这里插入图片描述

  • 自定义
    • @SentinelResource(value = “testHotKey”,blockHandler = “deal_testHotKey”) //value值与资源名一致即可
    • 方法testHostKey里面第一个参数只要QPS超过每秒1次马上降级处理
  • 测试
    • error 1秒1下可以但是超过则降级和p1参数有关
      http://localhost:8401/testHotKey?p1=abc
    • error1秒1下可以但是超过则降级和p1参数有关
      http://localhost:8401/testHotKey?p1=abc&p2=33
    • right狂点不会触发降级与p2参数无关
      http://localhost:8401/testHotKey?p2=abc

6.参数例外项

  • 上述案例演示了第一个参数p1,当QPS超过1秒1次点击后马上被限流

  • 特殊情况

    • 普通
    • 超过1秒钟一个后达到阈值1后马上被限流
    • 我们期望p1参数当它是某个特殊值时它的限流值和平时不一样
    • 特例
    • 假如当p1的值等于5时它的阈值可以达到200
  • 配置

    • 添加按钮不能忘
      在这里插入图片描述在这里插入图片描述
  • 测试
    http://localhost:8401/testHotKey?p1=5 对
    http://localhost:8401/testHotKey?p1=3 错

    • 当p1等于5的时候阈值变为200
    • 当p1不等于5的时候阈值就是平常的1
  • 前提条件

    • 热点参数的注意点参数必须是基本类型或者String
      在这里插入图片描述

7.其他

  • 手贱添加异常看看…
  • @SentinelResource
    • 处理的是Sentinel控制台配置的违规情况有blockHandler方法配置的兜底处理
  • RuntimeException
    • Int age = 10/0;这个是java运行时报出的运行时异常RuntimeExcepti- n@SentinelResource不管
  • 总结
    • @SentinelResource主管配置出错运行出错该走异常走异常

七、系统规则

1.是什么

[https://github.c- m/alibaba/Sentinel/wiki/%E7%B3%BB%E7%BB%9F%E8%87%AA%E9%80%82%E5%BA%94%E9%99%90%E6%B5%81](https://github.c- m/alibaba/Sentinel/wiki/%E7%B3%BB%E7%BB%9F%E8%87%AA%E9%80%82%E5%BA%94%E9%99%90%E6%B5%81)

2.各项配置参数说明

在这里插入图片描述

3.配置全局QPS

在这里插入图片描述

八、@SentinelResource

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

  • 启动Nac- s成功
  • 启动Sentinel成功
  • Module
    • cloudalibaba-sentinel-service8401
    • POM
    • YML
server:
  port: 8401

spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719  #默认8719应用与Sentinel控制台交互的端口应用本地会起一个该端口占用的HttpServer

management:
  endpoints:
    web:
      exposure:
        include: '*'
  • 业务类RateLimitController
package com.donglin.springcloud.alibaba.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.donglin.springcloud.alibaba.entities.CommonResult;
import com.donglin.springcloud.alibaba.entities.Payment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RateLimitController{
    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "handleException")
    public CommonResult byResource(){
        return new CommonResult(200,"按资源名称限流测试OK",new Payment(2020L,"serial001"));
    }
    public CommonResult handleException(BlockException exception){
        return new CommonResult(444,exception.getClass().getCanonicalName()+"\t 服务不可用");
    }
}
  • 主启动
package com.donglin.springcloud.alibaba;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@EnableDiscoveryClient
@SpringBootApplication
public class MainApp8401{
    public static void main(String[] args) {
        SpringApplication.run(MainApp8401.class, args);
    }
}
  • 配置流控规则

  • 配置步骤
    在这里插入图片描述

    • 图形配置和代码关系
    • 表示1秒钟内查询次数大于1就跑到我们自定义的处理限流
  • 测试

    • 1秒钟点击1下OK
    • 超过上述问题疯狂点击返回了自己定义的限流处理信息限流发生
  • 额外问题

    • 此时关闭微服务8401看看
    • Sentinel控制台流控规则消失了
    • 临时/持久

2.按照Url地址限流+后续处理

  • 通过访问的URL来限流会返回Sentinel自带默认的限流处理信息
  • 业务类RateLimitController
@GetMapping("/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl(){
    return new CommonResult(200,"按url限流测试OK",new Payment(2020L,"serial002"));
}
  • 访问一次

  • Sentinel控制台配置
    在这里插入图片描述

  • 测试

    • 疯狂点击http://localhost:8401/rateLimit/byUrl
    • 结果
    • 会返回Sentinel自带的限流处理结果
      在这里插入图片描述

3.上面兜底方法面临的问题

  • 系统默认的没有体现我们自己的业务要求。
  • 依照现有条件我们自定义的处理方法又和业务代码耦合在一起不直观。
  • 每个业务方法都增加一个兜底的那代码膨胀加剧。
  • 全局统一的处理方法没有体现。

4.客户自定义限流处理逻辑

  • 创建customerBlockHandler类用于自定义限流处理逻辑
  • 自定义限流处理类
  • 方法必须是public static修饰的。
package com.donglin.springcloud.alibaba.myhandler;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.donglin.springcloud.entities.CommonResult;

public class CustomerBlockHandler {
    public static CommonResult handleException(BlockException exception){
        return new CommonResult(2020,"自定义限流处理信息.... CustomerBlockHandler --- 1");
    }

    public static CommonResult handleException2(BlockException exception){
        return new CommonResult(2020,"自定义限流处理信息.... CustomerBlockHandler --- 2");
    }
}
  • RateLimitController
@GetMapping("/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler",
        blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handleException2")
public CommonResult customerBlockHandler(){
    return new CommonResult(200,"按客戶自定义",new Payment(2020L,"serial003"));
}
  • 启动微服务后先调用一次
    http://localhost:8401/rateLimit/customerBlockHandler
  • Sentinel控制台配置
  • 测试后我们自定义的出来了
  • 进一步说明
    在这里插入图片描述

5.更多注解属性说明

https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81
在这里插入图片描述

九、服务熔断功能

1.sentinel整合ribbon+openFeign+fallback

2.Ribbon系列

2.1 启动nacos和sentinel

2.2 提供者9003/9004

1)新建Modulecloudalibaba-provider-payment9003/9004
2)POM

<dependencies>
    <!--SpringCloud ailibaba nacos -->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <dependency><!-- 引入自己定义的api通用包可以使用Payment支付Entity -->
        <groupId>com.donglin.springcloud</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>${project.version}</version>
    </dependency>
    <!-- SpringBoot整合Web组件 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!--日常通用jar包配置-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3)YML

server:
  port: 9003

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址

management:
  endpoints:
    web:
      exposure:
        include: '*'
  • 记得修改不同的端口号
    4)主启动
package com.donglin.springcloud.alibaba;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

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

5)业务类

package com.donglin.springcloud.alibaba.controller;

import com.donglin.springcloud.alibaba.entities.CommonResult;
import com.donglin.springcloud.alibaba.entities.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;

@RestController
public class PaymentController{
    @Value("${server.port}")
    private String serverPort;

    public static HashMap<Long, Payment> hashMap = new HashMap<>();
    static{
        hashMap.put(1L,new Payment(1L,"28a8c1e3bc2742d8848569891fb42181"));
        hashMap.put(2L,new Payment(2L,"bba8c1e3bc2742d8848569891ac32182"));
        hashMap.put(3L,new Payment(3L,"6ua8c1e3bc2742d8848569891xt92183"));
    }

    @GetMapping(value = "/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
        Payment payment = hashMap.get(id);
        CommonResult<Payment> result = new CommonResult(200,"from mysql,serverPort:  "+serverPort,payment);
        return result;
    }

}

6)测试地址
http://localhost:9003/paymentSQL/1
http://localhost:9004/paymentSQL/1

2.3 消费者84

1)新建Modulecloudalibaba-consumer-nacos-order84
2)POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud2020</artifactId>
        <groupId>com.donglin.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>cloudalibaba-consumer-nacos-order84</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
        </dependency>
        <dependency>
            <groupId>com.donglin.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

3)YML

server:
  port: 84

spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:           
        dashboard: localhost:8080 #配置Sentinel dashboard地址
        port: 8719 #默认8719应用与Sentinel控制台交互的端口应用本地会起一个该端口占用的HttpServer

service-url:
  nacos-user-service: http://nacos-payment-provider

4)主启动

package com.donglin.springcloud.alibaba;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

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

5)业务类

  • ApplicationContextConfig
package com.donglin.springcloud.alibaba.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class ApplicationContextConfig{
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}
  • CircleBreakerController的全部源码
package com.donglin.springcloud.alibaba.controller;
 
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.donglin.springcloud.alibaba.entities.CommonResult;
import com.donglin.springcloud.alibaba.entities.Payment;
import com.donglin.springcloud.alibaba.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;

@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") //没有配置
    //@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规
    //@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler", exceptionsToIgnore = {IllegalArgumentException.class})
    public CommonResult<Payment> fallback(@PathVariable("id") Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(SERVICE_URL + "/paymentSQL/{id}", CommonResult.class,id);
        if (id == 4) {
            throw new IllegalArgumentException ("IllegalArgumentException,非法参数异常....");
        }else if (result.getData() == null) {
            throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
        }
        return result;
    }
}

2.4 目的

fallback管运行异常
blockHandler管配置违规
测试地址实现84对9003/9004的负载均衡
http://localhost:84/consumer/fallback/1
实验1.没有任何配置
@SentinelResource(value = “fallback”)//没有配置
给客户error页面不友好
在这里插入图片描述
在这里插入图片描述

实验2.只配置fallback

@SentinelResource(value = "fallback",fallback = "handlerFallback") //fallback只负责业务异常
    //fallback
    public CommonResult<Payment> handlerFallback(@PathVariable("id")  Long id,Throwable e) {
        Payment payment = new Payment(id,"null");
        return new CommonResult<Payment>(444,"兜底异常handlerFallback,exception内容  "+e.getMessage(),payment);
    }

测试出现异常会采用兜底方法展示错误消息
http://localhost:84/consumer/fallback/4
在这里插入图片描述

实验3.只配置blockHandler
@SentinelResource(value=“fallback”,blockHandler=“blockHandler”)//blockHandler只负责sentinel控制台配置违规

//blockHandler
public CommonResult<Payment> blockHandler(@PathVariable("id")  Long id, BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<Payment>(445,"blockHandler-sentinel限流,无此流水: blockException  "+blockException.getMessage(),payment);
}
  • 测试出现Java异常无人管
    http://localhost:84/consumer/fallback/4
    在这里插入图片描述

  • 测试出现查找不到数据异常无人管
    http://localhost:84/consumer/fallback/44
    在这里插入图片描述

  • 根据异常数进行降级处理
    在这里插入图片描述

  • 测试出现异常数超过2个降级处理
    在这里插入图片描述

实验4.fallback和blockHandler都配置
在这里插入图片描述

  • 结论
    http://localhost:84/consumer/fallback/4
    allback和blockHandler都配置不超过降级规则执行fallback兜底处理超过降级规则抛BlockException异常被blockHandler处理

实验5.忽略属性…
exceptionsToIgnore = {IllegalArgumentException.class}
不考虑降级违规情况发生IllegalArgumentException异常是不走兜底方法的。

3.Feign系列

1.修改84模块

  • 84消费者调用提供者9003
  • Feign组件一般是消费者
    2.POM
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

3.YML

server:
  port: 84

spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
    sentinel:
      transport:
        dashboard: localhost:8080
        port: 8719

service-url:
  nacos-user-service: http://nacos-payment-provider

#对Feign的支持

feign:
  sentinel:
    enabled: true

4.业务类

  • 带@FeignClient注解的业务接口
package com.donglin.springcloud.alibaba.service;

import com.donglin.springcloud.alibaba.entities.CommonResult;
import com.donglin.springcloud.alibaba.entities.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Component
@FeignClient(value = "nacos-payment-provider",fallback = PaymentFallbackService.class)
public interface PaymentFeignService{
    @GetMapping(value = "/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}
  • fallback = PaymentFallbackService.class
  • PaymentFallbackService实现类
package com.donglin.springcloud.alibaba.service;

import com.donglin.springcloud.alibaba.entities.CommonResult;
import com.donglin.springcloud.alibaba.entities.Payment;
import org.springframework.stereotype.Component;

@Component
public class PaymentFallbackService implements PaymentService{
    @Override
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
        return new CommonResult<>(44444,"服务降级返回,---PaymentFallbackService",new Payment(id,"errorSerial"));
    }
}
  • CircleBreakerController
// OpenFeign
@Resource
private PaymentFeignService paymentService;

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

5.主启动

  • 添加@EnableFeignClients启动Feign的功能
    6.http://localhost:84/consumer/paymentSQL/1
    7.测试84调用9003此时故意关闭9003微服务提供者看84消费侧自动降级不会被耗死

4.熔断框架比较

十、规则持久化

1.是什么

一旦我们重启应用Sentinel规则将消失生产环境需要将配置规则进行持久化

2.怎么玩

将限流配置规则持久化进Nacos保存只要刷新8401某个rest地址sentinel控制台的流控规则就能看到只要Nacos里面的配置不删除针对8401上Sentinel上的流控规则持续有效

3.步骤

1.修改cloudalibaba-sentinel-service8401
2.POM

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

3.YML

server:
  port: 8401

spring:
  application:
    name: cloudalibaba-sentinel-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos服务注册中心地址
    sentinel:
      transport:
        dashboard: localhost:8080 #配置Sentinel dashboard地址
        port: 8719
      datasource:
        ds1:
          nacos:
            server-addr: localhost:8848
            dataId: cloudalibaba-sentinel-service
            groupId: DEFAULT_GROUP
            data-type: json
            rule-type: flow

management:
  endpoints:
    web:
      exposure:
        include: '*'

feign:
  sentinel:
    enabled: true # 激活SentinelFeign的支持

4.添加Nacos业务规则配置

  • 内容解析
    在这里插入图片描述
[
    {
         "resource": "/rateLimit/byUrl",
         "limitApp": "default",
         "grade": 1,
         "count": 1,
         "strategy": 0,
         "controlBehavior": 0,
         "clusterMode": false 
    }
]

在这里插入图片描述

5.启动8401后刷新sentinel发现业务规则有了
在这里插入图片描述

6.快速访问测试接口
http://localhost:8401/rateLimit/byUrl
默认
在这里插入图片描述

7.停止8401再看sentinel
在这里插入图片描述

8.重新启动8401再看sentinel
扎一看还是没有稍等一会儿
多次调用
http://localhost:8401/rateLimit/byUrl
重新配置出现了持久化验证通过

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Spring