之前的限流是统计访问某个资源的所有请求,判断是否超过QPS阈值。而热点参数限流是分别统计参数值相同的请求,判断是否超过QPS阈值。

代表的含义是:
对hot这个资源的 0(第一个参数)做统计,每1秒相同参数值的请求数不能超过5次。
在热点参数限流的高级选项中,可以对部分参数设置例外配置:

注意:
热点参数限流对默认的SpringMVC资源无效,需要使用@SentinelResource() 注解,以及修改配置文件

给/order/getId/{orderId}这个资源添加热点参数限流,规则如下:
默认的热点参数规则是每1秒请求量不超过2
给215这个参数设置每1秒请求量不超过4
给216这个参数设置每1秒请求量不超过10


虽然限流可以尽量避免因高并发而引起的服务故障,但服务还会因为其它原因而故障。而要将这些故障控制在一定范围,避免雪崩,就要靠线程隔离(舱壁模式)和熔断降级手段了。 不管是线程隔离还是熔断降级,都是对客户端(调用方)的保护。
SpringCloud中,微服务调用都是通过Feign来实现的,因此做客户端保护必须整合Feign和Sentinel。
1.修改OrderService的application文件,开启Feign的Sentinel功能
- # 开启openfeign和sentinel整合
- feign.sentinel.enabled=true
2.给FeignClient编写失败后的降级逻辑
方式一:FallbackClass,无法对远程调用的异常做处理
方式二:FallbackFactory,可以对远程调用的异常做处理,本文选择这种
3.定义类,实现FallbackFactory:
- @Slf4j
- @Component
- public class ProductFeignFactory implements FallbackFactory
{ - @Override
- public ProductFeign create(Throwable throwable) {
- ProductFeign productFeign = new ProductFeign() {
- //兜底方案
- @Override
- public Product getById(Integer pid) {
- log.error("远程调用出现问题,执行了兜底方法");
- Product product = new Product();
- product.setPname("异常:"+throwable.getMessage());
- return product;
- }
- };
-
- return productFeign;
- }
- }
4. 为被容器的接口指定容错类
线程隔离有两种方式实现: 线程池隔离 信号量隔离(Sentinel默认采用)

信号量隔离:轻量级,无额外开销。但不支持主动超时,不支持异步调用。适用于高频调用,高扇出。
线程池隔离:支持主动超时,支持异步调用。但现成的额外开销比较大。适用于低扇出。
在添加限流规则时,可以选择两种阈值类型:

QPS:就是每秒的请求数,在快速入门中已经演示过
线程数:是该资源能使用用的tomcat线程数的最大值。也就是通过限制线程数量,实现舱壁模式。
需求:设置流控规则,线程数不能超过 2。然后利用jemeter测试。
熔断降级是解决雪崩问题的重要手段。其思路是由断路器统计服务调用的异常比例、慢请求比例,如果超出阈值则会熔断该服务。即拦截访问该服务的一切请求;而当服务恢复时,断路器会放行访问该服务的请求。

断路器熔断策略有三种:慢调用、异常比例、异常数
1.熔断策略-慢调用
慢调用:业务的响应时长(RT)大于指定时长的请求认定为慢调用请求。在指定时间内,如果请求数量超过设定的最小数量,慢调用比例大于设定的阈值,则触发熔断。例如:

解读:RT超过500ms的调用是慢调用,统计最近10000ms内的请求,如果请求量超过10次,并且慢调用比例不低于0.5,则触发熔断,熔断时长为5秒。然后进入half-open状态,放行一次请求做测试。
需求:设置降级规则,慢调用的RT阈值为100ms,统计时间为10秒,最小请求数量为5,失败阈值比例为0.5,熔断时长为30s

提示:为了触发慢调用规则,需要修改业务,增加业务耗时:


2.熔断策略-异常比例、异常数
异常比例或异常数:统计指定时间内的调用,如果调用次数超过指定请求数,并且出现异常的比例达到设定的比例阈值(或超过指定异常数),则触发熔断。例如:

解读:统计最近1000ms内的请求,如果请求量超过10次,并且异常比例不低于0.5,则触发熔断,熔断时长为5秒。然后进入half-open状态,放行一次请求做测试。
需求:设置降级规则,统计时间为10秒,最小请求数量为5,失败阈值比例为0.5,熔断时长为30s

提示:为了触发异常统计,需要修改业务,引发异常,进入兜底方法

熔断

容错类中拿到具体的错误,需要自定义异常类
默认情况下,发生限流、降级、授权拦截时,都会抛出异常到调用方。如果要自定义异常时的返回结果,需要实现BlockExceptionHandler接口:

而BlockException包含很多个子类,分别对应不同的场景:

自定义异常结果
- package com.zsy.order.hander;
-
- import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
- import com.alibaba.csp.sentinel.slots.block.BlockException;
- import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
- import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
- import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
- import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
- import org.springframework.stereotype.Component;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- @Component
- public class SentinelBlockHandler implements BlockExceptionHandler {
- @Override
- public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
- String msg = "未知异常";
- int status = 429;
- if (e instanceof FlowException) {
- msg = "请求被限流了!";
- }else if (e instanceof DegradeException) {
- msg = "请求被降级了!";
- } else if (e instanceof ParamFlowException) {
- msg = "热点参数限流!";
- } else if (e instanceof AuthorityException) {
- msg = "请求没有权限!";
- status = 401;
- }
- httpServletResponse.setContentType("application/json;charset=utf-8");
- httpServletResponse.setStatus(status);
- httpServletResponse.getWriter().println("{\"message\": \"" + msg + "\", \"status\": " + status + "}");
- }
- }

Sentinel的控制台规则管理有三种模式

原始模式:控制台配置的规则直接推送到Sentinel客户端,也就是我们的应用。然后保存在内存中,服务重启则丢失

pull模式:控制台将配置的规则推送到Sentinel客户端,而客户端会将配置规则保存在本地文件或数据库中。以后会定时去本地文件或数据库中查询,更新本地规则。

1 编写处理类
- package com.zsy.order.config;
-
- import com.alibaba.csp.sentinel.command.handler.ModifyParamFlowRulesCommandHandler;
- import com.alibaba.csp.sentinel.datasource.*;
- import com.alibaba.csp.sentinel.init.InitFunc;
- import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
- import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
- import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
- import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
- import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
- import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
- import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
- import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
- import com.alibaba.csp.sentinel.slots.system.SystemRule;
- import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
- import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.TypeReference;
- import org.springframework.beans.factory.annotation.Value;
-
- import java.io.File;
- import java.io.IOException;
- import java.util.List;
-
- public class FilePersistence implements InitFunc {
-
- @Value("${spring.application.name}")
- private String appcationName;
-
- @Override
- public void init() throws Exception {
- String ruleDir = "./sentinel-rules/" + appcationName;
- String flowRulePath = ruleDir + "/flow-rule.json";
- String degradeRulePath = ruleDir + "/degrade-rule.json";
- String systemRulePath = ruleDir + "/system-rule.json";
- String authorityRulePath = ruleDir + "/authority-rule.json";
- String paramFlowRulePath = ruleDir + "/param-flow-rule.json";
-
- this.mkdirIfNotExits(ruleDir);
- this.createFileIfNotExits(flowRulePath);
- this.createFileIfNotExits(degradeRulePath);
- this.createFileIfNotExits(systemRulePath);
- this.createFileIfNotExits(authorityRulePath);
- this.createFileIfNotExits(paramFlowRulePath);
-
- // 流控规则
- ReadableDataSource
> flowRuleRDS = new FileRefreshableDataSource<>( - flowRulePath,
- flowRuleListParser
- );
- FlowRuleManager.register2Property(flowRuleRDS.getProperty());
- WritableDataSource
> flowRuleWDS = new FileWritableDataSource<>(
- flowRulePath,
- this::encodeJson
- );
- WritableDataSourceRegistry.registerFlowDataSource(flowRuleWDS);
-
- // 降级规则
- ReadableDataSource
> degradeRuleRDS = new FileRefreshableDataSource<>( - degradeRulePath,
- degradeRuleListParser
- );
- DegradeRuleManager.register2Property(degradeRuleRDS.getProperty());
- WritableDataSource
> degradeRuleWDS = new FileWritableDataSource<>(
- degradeRulePath,
- this::encodeJson
- );
- WritableDataSourceRegistry.registerDegradeDataSource(degradeRuleWDS);
-
- // 系统规则
- ReadableDataSource
> systemRuleRDS = new FileRefreshableDataSource<>( - systemRulePath,
- systemRuleListParser
- );
- SystemRuleManager.register2Property(systemRuleRDS.getProperty());
- WritableDataSource
> systemRuleWDS = new FileWritableDataSource<>(
- systemRulePath,
- this::encodeJson
- );
- WritableDataSourceRegistry.registerSystemDataSource(systemRuleWDS);
-
- // 授权规则
- ReadableDataSource
> authorityRuleRDS = new FileRefreshableDataSource<>( - authorityRulePath,
- authorityRuleListParser
- );
- AuthorityRuleManager.register2Property(authorityRuleRDS.getProperty());
- WritableDataSource
> authorityRuleWDS = new FileWritableDataSource<>(
- authorityRulePath,
- this::encodeJson
- );
- WritableDataSourceRegistry.registerAuthorityDataSource(authorityRuleWDS);
-
- // 热点参数规则
- ReadableDataSource
> paramFlowRuleRDS = new FileRefreshableDataSource<>( - paramFlowRulePath,
- paramFlowRuleListParser
- );
- ParamFlowRuleManager.register2Property(paramFlowRuleRDS.getProperty());
- WritableDataSource
> paramFlowRuleWDS = new FileWritableDataSource<>(
- paramFlowRulePath,
- this::encodeJson
- );
- ModifyParamFlowRulesCommandHandler.setWritableDataSource(paramFlowRuleWDS);
- }
-
- private Converter
> flowRuleListParser = source -> JSON.parseObject( - source,
- new TypeReference
>() {
- }
- );
- private Converter
> degradeRuleListParser = source -> JSON.parseObject( - source,
- new TypeReference
>() {
- }
- );
- private Converter
> systemRuleListParser = source -> JSON.parseObject( - source,
- new TypeReference
>() {
- }
- );
-
- private Converter
> authorityRuleListParser = source -> JSON.parseObject( - source,
- new TypeReference
>() {
- }
- );
-
- private Converter
> paramFlowRuleListParser = source -> JSON.parseObject( - source,
- new TypeReference
>() {
- }
- );
-
- private void mkdirIfNotExits(String filePath) throws IOException {
- File file = new File(filePath);
- if (!file.exists()) {
- file.mkdirs();
- }
- }
-
- private void createFileIfNotExits(String filePath) throws IOException {
- File file = new File(filePath);
- if (!file.exists()) {
- file.createNewFile();
- }
- }
-
- private
String encodeJson(T t) { - return JSON.toJSONString(t);
- }
- }
2 添加配置
在resources下创建配置目录 META-INF/services ,然后添加文件
com.alibaba.csp.sentinel.init.InitFunc
在文件中添加配置类的全路径
com.zsy.order.config.FilePersistence
push模式:控制台将配置规则推送到远程配置中心,例如Nacos。Sentinel客户端监听Nacos,获取配置变更的推送消息,完成本地配置更新。
