目录
微服务调用链路中的某个服务故障,引起整个链路中的所有微服务都不可用,这就是雪崩。
解决雪崩问题的常见方式有四种:
超时处理:设定超时时间,请求超过一定时间没有响应就返回错误信息,不会无休止等待。
舱壁模式:限定每个业务能使用的线程数,避免耗尽整个tomcat的资源,因此也叫线程隔离。
熔断降级:由断路器统计业务执行的异常比例,如果超出阈值则会熔断该业务,拦截访问该业务的一切请求。
流量控制:限制业务访问的QPS,避免服务因流量的突增而故障。
什么是雪崩问题?
如何避免因瞬间高并发流量而导致服务故障?
如何避免因服务故障引起的雪崩问题?
服务保护技术对比
Sentinel是阿里巴巴开源的一款微服务流量控制组件。官网地址:home
Sentinel 具有以下特征:
sentinel官方提供了UI控制台,方便我们对系统做限流设置。大家可以在GitHub下载。课前资料提供了下载好的jar包:
如果要修改Sentinel的默认端口、账户、密码,可以通过下列配置:
要使用Sentinel肯定要结合微服务,这里我们使用SpringCloud实用篇中的cloud-demo工程。没有的小伙伴可以在课前资料中找到:
项目结构如下:
我们在order-service中整合Sentinel,并且连接Sentinel的控制台,步骤如下:
1.引入sentinel依赖:
com.alibaba.cloud spring-cloud-starter-alibaba-sentinel
2.配置控制台地址:
spring.cloud.sentinel.transport.dashboard=localhost:8080
3.访问微服务的任意端点,触发sentinel监控
簇点链路:就是项目内的调用链路,链路中被监控的每个接口就是一个资源。默认情况下sentinel会监控SpringMVC的每一个端点(Endpoint),因此SpringMVC的每一个端点(Endpoint)就是调用链路中的一个资源。
流控、熔断等都是针对簇点链路中的资源来设置的,因此我们可以点击对应资源后面的按钮来设置规则:
点击资源/order/{orderId}后面的流控按钮,就可以弹出表单。表单中可以添加流控规则,如下图所示:
其含义是限制 /order/{orderId}这个资源的单机QPS为1,即每秒只允许1次请求,超出的请求会被拦截并报错。
需求:给 /order/{orderId}这个资源设置流控规则,QPS不能超过 5。然后利用jemeter测试。
在添加限流规则时,点击高级选项,可以选择三种流控模式:
关联模式:统计与当前资源相关的另一个资源,触发阈值时,对当前资源限流
使用场景:比如用户支付时需要修改订单状态,同时用户要查询订单。查询和修改操作会争抢数据库锁,产生竞争。
业务需求是有限支付和更新订单的业务,因此当修改订单业务触发阈值时,需要对查询订单业务限流。
当/write资源访问量触发阈值时,就会对/read资源限流,避免影响/write资源。
需求:
需求:有查询订单和创建订单业务,两者都需要查询商品。针对从查询订单进入到查询商品的请求统计,并设置限流。
步骤:
Sentinel默认只标记Controller中的方法为资源,如果要标记其它方法,需要利用@SentinelResource注解,示例:
Sentinel默认会将Controller方法做context整合,导致链路模式的流控失效,需要修改application.yml,添加配置:
#关闭context整合 spring.cloud.sentinel.web-context-unify=false
流控效果是指请求达到流控阈值时应该采取的措施,包括三种:
warm up也叫预热模式,是应对服务冷启动的一种方案。请求阈值初始值是 threshold / coldFactor,持续指定时长后,逐渐提高到threshold值。而coldFactor的默认值是3.
例如,我设置QPS的threshold为10,预热时间为5秒,那么初始阈值就是 10 / 3 ,也就是3,然后在5秒后逐渐增长到10.
当请求超过QPS阈值时,快速失败和warm up 会拒绝新的请求并抛出异常。而排队等待则是让所有请求进入一个队列中,然后按照阈值允许的时间间隔依次执行。后来的请求必须等待前面执行完成,如果请求预期的等待时间超出最大时长,则会被拒绝。
例如:QPS = 5,意味着每200ms处理一个队列中的请求;timeout = 2000,意味着预期等待超过2000ms的请求会被拒绝并抛出异常
之前的限流是统计访问某个资源的所有请求,判断是否超过QPS阈值。而热点参数限流是分别统计参数值相同的请求,判断是否超过QPS阈值。
配置示例:
代表的含义是:对hot这个资源的0号参数(第一个参数)做统计,每1秒相同参数值的请求数不能超过5
在热点参数限流的高级选项中,可以对部分参数设置例外配置:
结合上一个配置,这里的含义是对0号的long类型参数限流,每1秒相同参数的QPS不能超过5,有两个例外:
给/order/{orderId}这个资源添加热点参数限流,规则如下:
虽然限流可以尽量避免因高并发而引起的服务故障,但服务还会因为其它原因而故障。而要将这些故障控制在一定范围,避免雪崩,就要靠线程隔离(舱壁模式)和熔断降级手段了。
不管是线程隔离还是熔断降级,都是对客户端(调用方)的保护。
SpringCloud中,微服务调用都是通过Feign来实现的,因此做客户端保护必须整合Feign和Sentinel。
1.修改OrderService的application.yml文件,开启Feign的Sentinel功能
feign.sentinel.enabled=true
2.给FeignClient编写失败后的降级逻辑
步骤一:在order项目中定义类,实现FallbackFactory:
步骤二:在feing-api项目中的DefaultFeignConfiguration类中将UserClientFallbackFactory注册为一个Bean:
- package com.xzj.order.feigin;
-
- import com.xzj.entity.Product;
- import feign.hystrix.FallbackFactory;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.stereotype.Component;
-
- /**
- * @author xuan
- */
- @Slf4j
- @Component
- public class ProductFeiginFactory implements FallbackFactory
{ - @Override
- public ProductFeigin create(Throwable throwable) {
- // 创建UserClient接口实现类,实现其中的方法,编写失败降级的处理逻辑
- ProductFeigin productFeigin = new ProductFeigin() {
- @Override
- public Product getById(Integer pid) {
- Product product = new Product();
- product.setPname("服务器正忙");
- return product;
- }
- };
-
- return productFeigin;
- }
- }
步骤三:在feing-api项目中的UserClient接口中使用UserClientFallbackFactory:
- package com.xzj.order.feigin;
-
- import com.xzj.entity.Product;
- import org.springframework.cloud.openfeign.FeignClient;
- import org.springframework.web.bind.annotation.GetMapping;
- import org.springframework.web.bind.annotation.PathVariable;
-
- @FeignClient(value = "nacos-product",fallbackFactory =ProductFeiginFactory.class)
- public interface ProductFeigin {
- @GetMapping("product/getById/{pid}")
- public Product getById (@PathVariable Integer pid);
- }
线程隔离有两种方式实现:
优缺点
在添加限流规则时,可以选择两种阈值类型:
熔断降级是解决雪崩问题的重要手段。其思路是由断路器统计服务调用的异常比例、慢请求比例,如果超出阈值则会熔断该服务。即拦截访问该服务的一切请求;而当服务恢复时,断路器会放行访问该服务的请求。
断路器熔断策略有三种:慢调用、异常比例、异常数
慢调用:业务的响应时长(RT)大于指定时长的请求认定为慢调用请求。在指定时间内,如果请求数量超过设定的
•最小数量,慢调用比例大于设定的阈值,则触发熔断。例如:
解读:RT超过500ms的调用是慢调用,统计最近10000ms内的请求,如果请求量超过10次,并且慢调用比例不低于0.5,则触发熔断,熔断时长为5秒。然后进入half-open状态,放行一次请求做测试。
需求:给 UserClient的查询用户接口设置降级规则,慢调用的RT阈值为50ms,统计时间为1秒,最小请求数量为5,失败阈值比例为0.4,熔断时长为5
提示:为了触发慢调用规则,我们需要修改UserService中的业务,增加业务耗时:
断路器熔断策略有三种:慢调用、异常比例或异常数
解读:统计最近1000ms内的请求,如果请求量超过10次,并且异常比例不低于0.5,则触发熔断,熔断时长为5秒。然后进入half-open状态,放行一次请求做测试。
需求:给 UserClient的查询用户接口设置降级规则,统计时间为1秒,最小请求数量为5,失败阈值比例为0.4,熔断时长为5s
提示:为了触发异常统计,我们需要修改UserService中的业务,抛出异常:
授权规则可以对调用方的来源做控制,有白名单和黑名单两种方式。
例如,我们限定只允许从网关来的请求访问order-service,那么流控应用中就填写网关的名称
Sentinel是通过RequestOriginParser这个接口的parseOrigin来获取请求的来源的。
例如,我们尝试从request中获取一个名为origin的请求头,作为origin的值:
@Component
public class HeaderOriginParser implements RequestOriginParser {
@Override
public String parseOrigin(HttpServletRequest request) {
String origin = request.getHeader("origin");
if(StringUtils.isEmpty(origin)){
return "blank";
}
return origin;
}
}
我们还需要在gateway服务中,利用网关的过滤器添加名为gateway的origin头:
spring:
cloud:
gateway:
default-filters:
- AddRequestHeader=origin,gateway # 添加名为origin的请求头,值为gateway
给/order/{orderId} 配置授权规则
默认情况下,发生限流、降级、授权拦截时,都会抛出异常到调用方。如果要自定义异常时的返回结果,需要实现BlockExceptionHandler接口:
而BlockException包含很多个子类,分别对应不同的场景:
我们在order-service中定义类,实现BlockExceptionHandler接口:
package com.xzj.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客户端,而客户端会将配置规则保存在本地文件或数据库中。以后会定时去本地文件或数据库中查询,更新本地规则。
首先 Sentinel 控制台通过 API 将规则推送至客户端并更新到内存中,接着注册的写数据源会将新的规则保存到本地的文件中。
步骤一:编写处理类
- package com.xzj.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);
- }
- }
-
步骤二:添加配置
在resources下创建配置目录 META-INF/services ,然后添加文件
com.alibaba.csp.sentinel.init.InitFunc
在文件中添加配置类的全路径
com.xzj.order.config.FilePersistence
push模式:控制台将配置规则推送到远程配置中心,例如Nacos。Sentinel客户端监听Nacos,获取配置变更的推送消息,完成本地配置更新。
push模式实现最为复杂,依赖于nacos,并且需要改在Sentinel控制台。整体步骤如下:
详细步骤可以参考课前资料的《sentinel规则持久化》:
步骤一:修改order-service服务,使其监听Nacos配置中心
具体步骤如下:
<dependency>
<groupId>com.alibaba.cspgroupId>
<artifactId>sentinel-datasource-nacosartifactId>
dependency>
配置nacos地址
spring:
cloud:
sentinel:
datasource:
flow:
nacos:
server-addr: localhost:8848 # nacos地址
dataId: orderservice-flow-rules
groupId: SENTINEL_GROUP
rule-type: flow # 还可以是:degrade、authority、param-flow
步骤二:修改sentinel-dashboard源码,添加nacos数据源
具体步骤如下:
<dependency>
<groupId>com.alibaba.cspgroupId>
<artifactId>sentinel-datasource-nacosartifactId>
dependency>
步骤三:修改sentinel-dashboard的源码,配置nacos数据源
具体步骤如下:
3.修改 com.alibaba.csp.sentinel.dashboard.controller.v2包下的FlowControllerV2类:
步骤四:修改sentinel-dashboard的源码,修改前端页面:
修改src/main/webapp/resources/app/scripts/directives/sidebar/目录下的sidebar.html文件:
修改src/main/webapp/resources/app/scripts/directives/sidebar/目录下的sidebar.html文件。
将其中的这部分注释打开:
修改其中的文本: