概述
sentinel以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。
sentinel主要特性: sentinel组件有两部分组成(前台+后台):
- 核心库(Java客户端)不依赖任何框架/库,能够运行于所有Java运行时环境,同时对Dubbo/spring cloud等框架也有较好的支持。
- 控制台(dashboard)基于spring boot开发,打包后可以直接运行,不需要额外的tomcat等应用容器。
下载sentinel-dashboard-1.7.0.jar,需要Java8环境并且8080端口不被占用,运行命令:
java -jar sentinel-dashboard-1.7.0.jar
登录sentinel管理界面http://localhost:8080,账号密码都为sentinel。
初始化工程
启动nacos8848。 新建cloudalibaba-sentinel-service8401模块。 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-sentinel</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-nacos-discovery</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>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>
application.yml
server:
port: 8401
spring:
application:
name: cloudalibaba-sentinel-service
cloud:
nacos:
discovery:
server-addr: localhost:8848
sentinel:
transport:
dashboard: localhost:8080
port: 8719
management:
endpoints:
web:
exposure:
include: '*'
MainApp8401
@EnableDiscoveryClient
@SpringBootApplication
public class MainApp8401 {
public static void main(String[] args) {
SpringApplication.run(MainApp8401.class,args);
}
}
FlowLimitController
@RestController
public class FlowLimitController {
@GetMapping("/testA")
public String testA() {
return "----testA";
}
@GetMapping("/testB")
public String testB() {
return "----testB";
}
}
sentinel使用懒加载机制,执行一次访问http://localhost:8401/testA
流控规则
资源名:唯一名称,默认请求路径。 针对来源:sentinel可以针对调用者进行限流,填写微服务名,默认default(不区分来源)。 阈值类型/单机阈值:
- QPS(每秒请求数量):当调用该API的QPS达到阈值的时候,进行限流。
- 线程数:当调用该API的线程数达到阈值的时候,进行限流。
是否集群:不需要集群。
流控模式:
- 直接:API达到限流条件时,直接限流。
- 关联:当关联的资源达到阈值时,就限流自己。
- 链路:只记录指定链路上的流量(指定资源从入口资源进来的流量,如果达到阈值,就进行限流)
流控效果:
- 快速失败:直接失败,抛异常。
- Warm Up:根据codeFactor(冷加载因子,默认3)的值,从阈值/codeFactor开始,经过预热时长,才达到设置的QPS阈值。
- 排队等待:匀速排队,让请求以匀速的速度通过,阈值类型必须设置为QPS,否则无效。
QPS直接快速失败
配置流控规则: qps超过1则限流。
关联
当关联的资源/testB的qps超过阈值1后,就限流/testA自己。
预热
阈值为10,预热时长设置5秒,系统初始化的阈值为10/3约等于3,即阈值刚开始为3,然后过5秒后阈值才慢慢升高恢复到10。
秒杀系统在开启瞬间,会有很多流量上来,很有可能把系统打死,预热方式就是为了保护系统,慢慢把流量放进来。
排队等待
匀速排队,让请求以均匀的速度通过,阈值类型必须设成QPS,否则无效。对应的是漏桶算法。
/testA每秒1次请求,超时的话就排队等待,等待的超时时间为20000毫秒。
降级规则
RT(平均响应时间,秒级):平均响应时间超出阈值且在时间窗口内通过的请求>=5,两个条件同时满足后触发降级,窗口期过后关闭断路器,RT最大4900(更大的需要通过-Dcsp.sentinel.statistic.max.rt=XXXX才能生效)。
异常比例(秒级):QPS>=5且异常比例(秒级统计)超过阈值,触发降级;时间窗口结束后,关闭降级。
异常数(分钟级):异常数(分钟统计)超过阈值,触发降级;时间窗口结束后,关闭降级。
sentinel熔断降级会在调用链路中某个资源出现不稳定状态时(例如调用超时或异常比例升高),对这个资源的调用进行限制,让请求快速失败,避免影响到其他的资源而导致级联错误。
当资源被降级后,在接下类的降级时间窗口之内,对该资源的调用都自动熔断(默认行为是抛出DegradeException)。
sentinel断路器是没有半开状态的。
半开状态系统自动去检测是否请求有异常,没有异常就关闭断路器恢复使用,有异常则继续打开断路器不可用,可参考hystrix。
RT
@GetMapping("/testD")
public String testD() {
try{ TimeUnit.SECONDS.sleep(1); } catch(InterruptedException e) { e.printStackTrace(); }
return "----testD";
}
设置sentinel: 配置jmeter: 一秒钟打进来10个线程调用testD,并且一个线程需要处理1秒,所以断路器打开,微服务不可用。
异常比例
@GetMapping("/testD")
public String testD() {
int a = 10 / 0;
return "----testD";
}
异常数
@GetMapping("/testD")
public String testD() {
int a = 10 / 0;
return "----testD";
}
刚开始访问报错,达到五次报错后,进入熔断降级。
热点key限流
热点即经常访问的数据。很多时候我们希望统计某个热点数据中访问频次最高的TopK数据,并对其访问进行限制。比如:
- 商品ID为参数,统计一段时间内最常购买的商品ID并进行限制。
- 用户ID为参数,针对一段时间内频繁访问的用户ID并进行限制。
热点参数限流会统计传入参数中的热点参数,并根据配置的限流阈值与模式,对包含热点参数的资源调用进行限流。热点参数限流可以看作是一种特殊的流量控制,仅对包含热点参数的资源调用生效。
@GetMapping("/testHotKey")
@SentinelResource(value = "testHotKey", blockHandler = "deal_testHotKey")
public String testHotKey(@RequestParam(value = "p1",require = false) String p1, @RequestParam(value = "p2",require = false) String p2) {
return "testHotKey";
}
public String deal_testHotKey(String p1, String p2, BlockException ex) {
return "deal_testHotKey";
}
方法testHotKey里面第一个参数只要QPS超过每秒1次,马上降级处理。
参数例外项
如果期望p1参数当它是某个特殊值时,它的限流值和平时不一样。假如当p1的值等于5时,它的阈值可以达到200。
系统规则
系统保护规则是从应用级别的入口流量进行控制,从单台机器的load、CPU使用率、平均RT、入口QPS和并发线程数等几个维度监控应用指标,让系统尽可能跑在最大吞吐量的同时保证系统整体的稳定性。
系统保护规则是应用整体维度的,而不是资源维度的,并且仅对入口流量生效。入口流量指的是进入应用的流量,比如web服务或dubbo服务端接收的请求,都属于入口流量。
系统规则支持以下的模式:
- load自适应(仅对linux/unix-like机器生效):系统的load1作为启发指标,进行自适应系统保护。当系统load1超过设定的启发值,且系统当前的并发线程数超过估算的系统容量时才会触发系统保护(BBR阶段)。系统容量由系统的maxQps * minRt估算得出。设定参考值一般CPU cores * 2.5。
- CPU usage:当系统CPU使用率超过阈值即触发系统保护(取值范围0.0-1.0),比较灵敏。
- 平均RT:当单台机器上所有入口流量的平均RT达到阈值即触发系统保护,单位是毫秒。
- 并发线程数:当单台机器上所有入口流量的并发线程数达到阈值即触发系统保护。
- 入口QPS:当单台机器上所有入口流量的QPS达到阈值即触发系统保护。
@SentinelResource配置
按资源名称限流
@RestController
public class RateLimitController {
@GetMapping(value = "/byResource")
@SentinelResource(value = "byResource", blockHandler = "handleException")
public CommonResult byResource() {
return new CommonResult(200,"OK",new Payment(2020L,"serial001"));
}
public CommonResult handleException(BlockException ex) {
return new CommonResult(444,ex.getClass().getCanonicalName());
}
}
按URL地址限流
@RestController
public class RateLimitController {
@GetMapping(value = "/rateLimit/byUrl")
@SentinelResource(value = "byUrl")
public CommonResult byUrl() {
return new CommonResult(200,"OK",new Payment(2020L,"serial002"));
}
}
自定义限流处理逻辑
RateLimitController
@RestController
public class RateLimitController {
@GetMapping(value = "/rateLimit/customerBlockHandler")
@SentinelResource(value = "customerBlockHandler", blockHandlerClass = CustomerBlockHandler.class, blockHandler = "handlerException2")
public CommonResult customerBlockHandler() {
return new CommonResult(200,"OK",new Payment(2020L,"serial002"));
}
}
CustomerBlockHandler
public class CustomerBlockHandler{
public static CommonResult handlerException1(BlockException ex) {
return new CommonResult(4441,ex.getClass().getCanonicalName());
}
public static CommonResult handlerException2(BlockException ex) {
return new CommonResult(4442,ex.getClass().getCanonicalName());
}
}
服务熔断功能
基本环境搭建
sentinel整合ribbon+openFeign+fallback 服务提供者 创建cloudalibaba-provider-payment9003/9004模块
server:
port: 9003
spring:
application:
name: nacos-payment-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848
management:
endpoints:
web:
exposure:
include: '*'
PaymentMain9003
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain9003{
public static void main(String[] args) {
SpringApplication.run(PaymentMain9003.class,args);
}
}
PaymentController
@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,"111"));
hashMap.put(2L,new Payment(2L,"222"));
hashMap.put(3L,new Payment(3L,"333"));
}
@GetMapping("/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
Payment payment = hashMap.get(id);
CommonResult<Payment> result = new CommonResult(200,"ok"+serverPort,payment);
return result;
}
}
服务消费者 创建cloudalibaba-consumer-nacos-order84模块.
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
OrderNacosMain84
@SpringBootApplication
@EnableDiscoveryClient
public class OrderNacosMain84{
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class,args);
}
}
ApplicationContextConfig
@Configuration
public class ApplicationContextConfig{
@Bean
@LoadBalanced
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
CircleBreakerController
@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("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");
}
return result;
}
}
服务熔断无配置
CircleBreakerController
@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("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");
}
return result;
}
}
访问http://localhost:84/consumer/fallback/4时返回error内容。
服务熔断只配置fallback
CircleBreakerController
@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",fallback = "handlerFallback")
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");
}
return result;
}
public CommonResult<Payment> handlerFallback(@PathVariable("id") Long id, Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>("444","兜底异常handlerFallback"+e.getMessage(),payment);
}
}
访问http://localhost:84/consumer/fallback/4时返回fallback内容。
服务熔断只配置blockHandler
CircleBreakerController
@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", blockHandler = "blockHandler")
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");
}
return result;
}
public CommonResult<Payment> blockHandler(@PathVariable("id") Long id, BlockException e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>("444","BlockException "+e.getMessage(),payment);
}
}
每秒一次访问http://localhost:84/consumer/fallback/4时返回error内容。 每秒多次访问http://localhost:84/consumer/fallback/4时返回blockHandler内容。
服务熔断配置fallback和blockHandler
CircleBreakerController
@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", fallback = "handlerFallback", blockHandler = "blockHandler")
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");
}
return result;
}
public CommonResult<Payment> blockHandler(@PathVariable("id") Long id, BlockException e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>("444","BlockException "+e.getMessage(),payment);
}
public CommonResult<Payment> handlerFallback(@PathVariable("id") Long id, Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>("444","兜底异常handlerFallback"+e.getMessage(),payment);
}
}
每秒一次访问http://localhost:84/consumer/fallback/1时返回正常数据。 每秒多次访问http://localhost:84/consumer/fallback/1时返回blockHandler内容。 每秒一次访问http://localhost:84/consumer/fallback/4时返回fallback内容。 每秒多次访问http://localhost:84/consumer/fallback/4时返回blockHandler内容。
服务熔断配置exceptionsToIgnore
CircleBreakerController
@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", 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");
}
return result;
}
public CommonResult<Payment> blockHandler(@PathVariable("id") Long id, BlockException e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>("444","BlockException "+e.getMessage(),payment);
}
public CommonResult<Payment> handlerFallback(@PathVariable("id") Long id, Throwable e) {
Payment payment = new Payment(id,"null");
return new CommonResult<>("444","兜底异常handlerFallback"+e.getMessage(),payment);
}
}
如果报IllegalArgumentException,不再有fallback方法兜底,没有降级效果。
服务熔断配置OpenFeign
修改cloudalibaba-consumer-nacos-order84模块 pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
application.yml
feign:
sentinel:
enable: true
OrderNacosMain84
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderNacosMain84{
public static void main(String[] args) {
SpringApplication.run(OrderNacosMain84.class,args);
}
}
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","服务降级返回",new Payment(id,"null"));
}
}
CircleBreakerController
@RestController
@Slf4j
public class CircleBreakerController{
public static final String SERVICE_URL = "http://nacos-payment-provider";
@Resource
private RestTemplate restTemplate;
@Resource
private PaymentService paymentService;
@GetMapping(value = "/consumer/paymentSQL/{id}")
public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id) {
return paymentService.paymentSQL(id);
}
}
规则持久化
一旦重启应用,sentinel规则将消失,生产环境需要将配置规则进行持久化。
将限流配置规则持久化进Nacos保存,只要刷新8401某个rest地址,sentinel控制台的流控规则就能看到,只要nacos里面的配置不删除,针对8401上sentinel上的流控规则持续生效。
修改cloudalibaba-sentinel-service8401模块。 pom.xml
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
</dependency>
application.yml
spring:
cloud:
sentinel:
datasource:
dsl:
nacos:
server-addr: localhost:8848
dataId: cloudalibaba-sentinel-service
groupId: DEFAULT_GROUP
data-type: json
rule-type: flow
resource:资源名称 limitApp:来源应用 grade:阈值类型,0表示线程数,1表示qps count:单机阈值 strategy:流控模式,0表示直接,1表示关联,2表示链路 controlBehavior:流控效果,0表示快速失败,1表示warm up,2表示排队等待 clusterMode:是否集群
启动8401,刷新http://localhost:8401/rateLimit/byUrl
|