目录
1.简介
GitHub官方:https://github.com/alibaba/Sentinel
中午:https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D
一句话:Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
2.安装
2.1 下载
官方下载地址:https://github.com/alibaba/Sentinel/releases
百度云盘链接:https://pan.baidu.com/s/1QzVfCbNh6dHevPVi9pToww
提取码:l0o1
2.2 安装
当前目录运行cmd
java -jar sentinel-dashboard-1.8.2.jar
2.3 访问
http://localhost:8080
3.测试
3.1 新建cloudalibaba-sentinel-service8401
3.2 Pom.xml
<dependencies>
<dependency>
<groupId>com.atguigu.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.3 bootstrap.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,假如被占用了会自动从8719开始依次+1扫描。直至找到未被占用的端口
management:
endpoints:
web:
exposure:
include: '*'
3.4 FlowLimitController.java
package com.node.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class FlowLimitController
{
@GetMapping("/testA")
public String testA() {
return "testA测试成功";
}
@GetMapping("/testB")
public String testB() {
return "testB测试成功";
}
}
3.5 MainApp8401.java
package com.node;
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);
}
}
3.6 运行nacos、sentinel、运行8401
4.流控规则(流量控制配置)
1.资源名:唯一名称,默认请求路径
2.针对来源: Sentinel可以针对调用者进行限流,填写微服务名,默认default (不区分来源)
3.阈值类型/单机阈值:
- QPS(每秒钟的请求数量):当调用该api的QPS达到阈值的时候,进行限流。
- 线程数(多人使用,不是同线程):当调用i该api的线程数达到阈值的时候,进行限流。
4.流控模式:
- 直接:api达到限流条件时,直接限流
- 关联:当关联的资源达到阈值时,就限流自己。(关联testB,当testB达到阈值,限流testA)
- 链路:只记录指定链路上的流量(指定资源从入口资源进来的流量,如果达到阈值,就进行限流)【api级别的针对来源】
5.流控效果:
- 快速失败:直接失败,抛异常
- Warm Up(预热):根据codeFactor(冷加载因子,默认3)的值,从阈值除以codeFactor,经过预热时长,才达到设置的QPS阈值。(当阈值为10,10/3=3,当每秒钟的请求数量超过3时,则限流,后面慢慢开放)
- 排队等待(一个一个进):匀速排队,让请求以匀速的速度通过,阈值类型必须设置为QPS,否则无效
5.降级规则(服务降级熔断器)
RT(平均响应时间,秒级)
- 平均响应时间超出阈值且在时间窗口内通过的请求>=5,两个条件同时满足后触发降级
- 窗口期过后关闭断路器
- RT最大4900(更大的需要通过-Dcsp.sentinel.statistic.max.rt=XXXX才能生效)
异常比列(秒级)
- QPS >= 5且异常比例(秒级统计)超过阈值时,触发降级;时间窗口结束后,关闭降级
异常数(分钟级)
- 异常数(分钟统计)超过阈值时,触发降级;时间窗口结束后,关闭降级
5.1 RT
平均响应时间:当1s内持续进入5个请求,对应时刻的平均响应时间(秒级)均超过阈值( count,以ms为单位),那么在接下的时间窗口(以s为单位)之内,对这个方法的调用都会自动地熔断(抛出DegradeException )。
满足服务降级的两个条件:1s内进入5个请求+RT毫秒内没有完成当前1个请求=降级熔断
注意:1.8版本之后有半熔断,之前没有
5.1.1 测试
5.1.1.1 修改FlowLimitController.java
@GetMapping("/testC")
public String testC()
{
//每执行一个请求需要1s
try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
log.info("testC 测试RT");
return "------testC";
}
5.1.1.2 开启jmeter
5.1.1.3 运行后配置降级规则
5.1.1.4 运行
满足要求1:1s睡眠(sleep(1))>200ms 完成一个请求实际为1秒,可要求为200毫秒
满足要求2:1s内进入10个请求>5个请求
当关闭压力测试,1s后恢复正常
5.2 异常比例
异常比例( DEGRADE_GRADE_EXCEPTION_RATIo ):当资源的每秒请求量>=5,并且每秒异常总数占通过量的比值超过阈值之后,资源进入降级状态,即在接下的时间窗口之内,对这个方法的调用都会自动地返回。异常比率的阈值范围是[0.0,1.0],代表0% - 100%。
满足服务降级的两个条件:1s内进入5个请求+5次请求失败率大于设定阈值=降级熔断
5.2.1 测试
5.2.1.1 修改FlowLimitController.java
@GetMapping("/testD")
public String testD()
{
log.info("testD 测试RT");
int age = 10/0; //每次请求都为错误异常请求
return "------testD";
}
5.2.1.2 开启jmeter
5.2.1.3 运行后配置降级规则
5.1.1.4 运行
正常情况:
开启压力测试
满足要求1:1s内进入10个请求>5个请求
满足要求2:错误率大于设定阈值百分之50(0.5)
恢复后:
5.3 异常数
异常数( DEGRADE_GRADE_EXCEPTION_COUNT ):当资源近1分钟的异常数目超过阈值之后会进行熔断。注意由于统计时间窗口是分钟级别的,若 timewindow小于60s,则结束熔断状态后仍可能再进入镕断状态。
6.热点规则(根据传递的参数进行配置)
简单来说热点规则是对ip地址的参数进行限流
6.1 测试
6.1.1 修改FlowLimitController.java
@GetMapping("/testHotKey")
@SentinelResource(value = "testHotKey",blockHandler = "deal_testHotKey")
//value = "testHotKey":对应上Sentinel的热点规则的资源名称
// blockHandler = "deal_testHotKey" :服务降级方法
//required = false:传入的参数值可填可不填
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 "testHotKey出现异常!!!!!";
}
@SentinelResource与Hystrix断路器的@HystrixCommand用法基本一样
6.1.2 运行后配置热点规则
6.1.3 测试
6.2 热点规则高级选项
6.2 当服务代码出现有异常时
直接报500错误
原因:@SentinelResource的blockHandler处理的是sentinel控制台配置的违规情况,下面的降级方法也只是针对sentinel的。int age = 10/0,这个是java运行时报出的运行时异常RunTimeException,@SentinelResource不管。
@sentinelResource的blockHandler只管配置出错,运行出错该走异常走异常,
fallback参数管java
7.系统规则
系统保护规则是从应用级别的入口流量进行控制,从单台机器的 load、CPU使用率、平均RT、入口QPS和并发线程数等几个维度监控应用指标,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。简单来说,对整个工程的限流规则
- Load自适应:(仅对Linux/Unix-like机器生效):系统的load1作为启发指标,进行自适应系统保护。当系统load1超过设定的启发值,且系统当前的并发线程数超过估算的系统容量时才会触发系统保护(BBR阶段)。
- CPU使用率︰当系统CPU使用率超过阈值即触发系统保护(取值范围0.0-1.0),比较灵敏。
- 平均RT:当单台机器上所有入口流量的平均RT达到阈值即触发系统保护,单位是毫秒。
- 并发线程数:当单台机器上所有入口流量的并发线程数达到阈值即触发系统保护。
- 入口QPS:当单台机器上所有入口流量的QPS达到阈值即触发系统保护。
8.@SentinelResource
8.1 资源名的应用
8.1.1 按资源名称限流
8.1.2 按照Url地址限流
9. 客户自定义限流处理逻辑
目的:
- 系统默认的降级方法(页面),没有体现我们自己的业务要求。
- 依照现有条件,我们自定义的处理方法又和业务代码耦合在一块,不直观。每个业务方法都添加一个降级方法,那代码膨胀加剧。
- 全局统一的处理方法没有体现。
8.2.1 创建customerBlockHandler.java用于自定义限流处理逻辑
package com.node.handler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.node.entities.CommonResult;
public class CustomerBlockHandler {
public static CommonResult handleException(BlockException exception) {
return new CommonResult(2020, "自定义限流处理信息....handleException");
}
public static CommonResult handleException2(BlockException exception) {
return new CommonResult(2020, "自定义限流处理信息....handleException2");
}
}
8.2.2 修改FlowLimitController.java
/**
* 自定义限流处理信息
*/
@GetMapping("/testE")
@SentinelResource(value = "testE",
blockHandlerClass= CustomerBlockHandler.class,
blockHandler ="handleException2")
public String testE()
{
return "------testE";
}
8.2.3 测试
10.sentinel整合ribbon
细节:@SentinelResource的blockHandler熔断方法只管sentinel配置的错误,fallback熔断方法管java运行的错误
10.1 启动nacos和sentinel
10.2 新建cloudalibaba-provider-payment9003/9004
10.2.1 Pom.xml
<?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>SpringCloud</artifactId>
<groupId>org.example</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-provider-payment9003</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency><!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
<groupId>org.example</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</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>
</project>
10.2.2 application.yml
server:
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
management:
endpoints:
web:
exposure:
include: '*'
10.2.3 PaymentController.java
package com.node.Controller;
import com.node.entities.CommonResult;
import com.node.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;
}
}
10.2.4 PaymentMain9003.java
package com.node;
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);
}
}
10.2.5 测试
10.3 新建cloudalibaba-consumer-nacos-order84
10.3.1 Pom.xml
<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>org.example</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</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>
10.3.2 application.xml
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
10.3.3 ApplicationContextConfig.java
package com.node.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();
}
}
10.3.4 CircleBreakerController.java
package com.node.controller;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.node.entities.CommonResult;
import com.node.entities.Payment;
import lombok.extern.slf4j.Slf4j;
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",fallback = "handlerFallback") //fallback只负责业务异常,当代运行有问题,就跳到降级方法
//@SentinelResource(value = "fallback",blockHandler = "blockHandler") //blockHandler只负责sentinel控制台配置违规,当超过sentinel控制台配置范围,就跳到降级方法
@SentinelResource(value = "fallback",fallback = "handlerFallback",blockHandler = "blockHandler"//都配置了,blockHandler(最底层降级)>fallback
) //exceptionsToIgnore = {IllegalArgumentException.class}如果执行了IllegalArgumentException,则不跳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 ("IllegalArgumentException,非法参数异常....");
}else if (result.getData() == null) {
throw new NullPointerException ("NullPointerException,该ID没有对应记录,空指针异常");
}
return result;
}
//fallback
public CommonResult handlerFallback(@PathVariable Long id, Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(444,"兜底异常handlerFallback,exception内容 "+e.getMessage(),payment);
}
//blockHandler
public CommonResult blockHandler(@PathVariable Long id, BlockException blockException) {
Payment payment = new Payment(id,"null");
return new CommonResult<>(445,"blockHandler-sentinel限流,无此流水: blockException "+blockException.getMessage(),payment);
}
}
10.3.5 测试
配置sentinel
11.sentinel整合Feign
11.1 修改cloudalibaba-consumer-nacos-order84
11.2 Pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
11.3 application.yml
#对Feign的支持
feign:
sentinel:
enabled: true
11.4 Service层
11.4.1 PaymentService.java
package com.node.service;
import com.node.entities.CommonResult;
import com.node.entities.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(value = "nacos-payment-provider",fallback = PaymentServiceImpl.class) //Feign调用
//fallback = PaymentServiceImpl.class。 当无法调用9003和9004的时候 就会跳到PaymentServiceImpl方法
public interface PaymentService
{
@GetMapping(value = "/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id);
}
11.4.2 PaymentServiceImpl.java
package com.node.service;
import com.node.entities.CommonResult;
import com.node.entities.Payment;
import org.springframework.stereotype.Component;
@Component
public class PaymentServiceImpl implements PaymentService{
@Override
public CommonResult<Payment> paymentSQL(Long id) {
return new CommonResult<>(44444,"服务降级返回,---PaymentFallbackService",new Payment(id,"errorSerial"));
}
}
11.5 CircleBreakerController.java
//feign调用
// OpenFeign
@Resource
private PaymentService paymentService;
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
return paymentService.paymentSQL(id);
}
11.6 测试
12.规则持久化
一旦我们重启应用,Sentinel规则将消失,生产环境需要将配置规则进行持久化
操作方法:
将限流配置规则持久化进Nacos保存,只要重启后刷新84的地址,sentinel控制台的流控规则就能看到,只要Nacos里面的配置不删除,针对84的Sentinel上的流控规则持续有效
12.1 修改cloudalibaba-consumer-nacos-order84
12.2 Pom.xml
<!--sentinel持久化资源配置-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
12.3 application.yml
datasource:
ds1:
nacos:
server-addr: localhost:8848
dataId: nacos-order-consumer
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
management:
endpoints:
web:
exposure:
include: '*'
12.4 配置nacos
[
{
"resource":"GET:http://nacos-user-server/user/list",
"limitApp":"default",
"grade": 1,
"count": 1,
"strategy": 0,
"controlBehavior": 0,
"clusterMode": false
}
]
12.5 重新启动测试
这样以后这个ip地址就不用每次都配置sentinel了,只需在nacos配置一次即可实现持久化