IDC

微服务限流容错降级Sentinel实战

作者:admin 2021-04-26 我要评论

一、什么是雪崩效应? 业务场景,高并发调用 正常情况下,微服务A B C D 都是正常的。 随着时间推移,在某一个时间点 微服务A突然挂了,此时的微服务B 还在疯狂的...

在说正事之前,我要推荐一个福利:你还在原价购买阿里云、腾讯云、华为云服务器吗?那太亏啦!来这里,新购、升级、续费都打折,能够为您省60%的钱呢!2核4G企业级云服务器低至69元/年,点击进去看看吧>>>)

 一、什么是雪崩效应?

业务场景,高并发调用

  1. 正常情况下,微服务A B C D 都是正常的。
  2. 随着时间推移,在某一个时间点 微服务A突然挂了,此时的微服务B 还在疯狂的调用微服务A,由于A已经挂了,所以B调用A必须等待服务调用超时。而我们知道每次B -> A 的适合B都会去创建线程(而线程由计算机的资源,比如cpu、内存等)。由于是高并发场景,B 就会阻塞大量的线程。那边B所在的机器就会去创建线程,但是计算机资源是有限的,最后B的服务器就会宕机。(说白了微服务B 活生生的被猪队友微服务A给拖死了)
  3. 由于微服务A这个猪队友活生生的把微服务B给拖死了,导致微服务B也宕机了,然后也会导致微服务 C D 出现类似的情况,最终我们的猪队友A成功的把微服务 B C D 都拖死了。这种情况也叫做服务雪崩。也有一个专业术语(cascading failures)级联故障。

二、容错三板斧

2.1 超时

简单来说就是超时机制,配置以下超时时间,假如1秒——每次请求在1秒内必须返回,否则到点就把线程掐死,释放资源!

思路:一旦超时,就释放资源。由于释放资源速度较快,应用就不会那么容易被拖死。

代码演示:(针对调用方处理)

  1. // 第一步:设置RestTemplate的超时时间 
  2. @Configuration 
  3. public class WebConfig { 
  4.  
  5.     @Bean 
  6.     public RestTemplate restTemplate() { 
  7.         //设置restTemplate的超时时间 
  8.         SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); 
  9.         requestFactory.setReadTimeout(1000); 
  10.         requestFactory.setConnectTimeout(1000); 
  11.         RestTemplate restTemplate = new RestTemplate(requestFactory); 
  12.         return restTemplate; 
  13.     } 
  14.  
  15. // 第二步:进行超时异常处理 
  16. try{ 
  17.     ResponseEntity<ProductInfo> responseEntity= restTemplate.getForEntity(uri+orderInfo.getProductNo(), ProductInfo.class); 
  18.     productInfo = responseEntity.getBody(); 
  19. }catch (Exception e) { 
  20.     log.info("调用超时"); 
  21.     throw new RuntimeException("调用超时"); 
  22.  
  23.  
  24. // 设置全局异常处理 
  25. @ControllerAdvice 
  26. public class NiuhExceptionHandler { 
  27.  
  28.     @ExceptionHandler(value = {RuntimeException.class}) 
  29.     @ResponseBody 
  30.     public Object dealBizException() { 
  31.         OrderVo orderVo = new OrderVo(); 
  32.         orderVo.setOrderNo("-1"); 
  33.         orderVo.setUserName("容错用户"); 
  34.         return orderVo; 
  35.     } 

 2.2 舱壁隔离模式


有兴趣可以先了解一下船舱构造——一般来说,现代的轮船都会分很多舱室,舱室直接用钢板焊死,彼此隔离。这样即使有某个/某些船舱进水,也不会营销其它舱室,浮力够,船不会沉。

代码中的舱壁隔离(线程池隔离模式)

M类使用线程池1,N类使用线程池2,彼此的线程池不同,并且为每个类分配的线程池大小,例如 coreSIze=10。

举例子:M类调用B服务,N类调用C服务,如果M类和N类使用相同的线程池,那么如果B服务挂了,N类调用B服务的接口并发又很高,你又没有任何保护措施,你的服务就很可能被M类拖死。而如果M类有自己的线程池,N类也有自己的线程池,如果B服务挂了,M类顶多是将自己的线程池占满,不会影响N类的线程池——于是N类依然能正常工作。

  • 思路:不把鸡蛋放在一个篮子里,你有你的线程池,我有我的线程池,你的线程池满类和我也没关系,你挂了也和我也没关系。

2.3 断路器模式

现实世界的断路器大家肯定都很了解,每个人家里都会有断路器。断路器实时监控电路的情况,如果发现电路电流异常,就会跳闸,从而防止电路被烧毁。

软件世界的断路器可以这样理解:实时监测应用,如果发现在一定时间内失败次数/失败率达到一定阀值,就“跳闸”,断路器打开——次数,请求直接返回,而不去调用原本调用的逻辑。

跳闸一段时间后(例如15秒),断路器会进入半开状态,这是一个瞬间态,此时允许一个请求调用该调的逻辑,如果成功,则断路器关闭,应用正常调用;如果调用依然不成功,断路器继续回到打开状态,过段时间再进入半开状态尝试——通过“跳闸”,应用可以保护自己,而且避免资源浪费;而通过半开的设计,可以实现应用的“自我修复”

三、Sentinel 流量控制、容错、降级

3.1 什么是Sentinel?

A lightweight powerful flow control component enabling reliability and monitoring for microservices.(轻量级的流量控制、熔断降级 Java 库) github官网地址:https://github.com/alibaba/Sentinelwiki:https://github.com/alibaba/Sentinel/wiki/

  • Hystrix 在 Sentinel 面前就是弟弟

Sentinel的初体验

niuh04-ms-alibaba-sentinel-helloworld

V1版本:

第一步:添加依赖包

  1. <!--导入Sentinel的相关jar包--> 
  2. <dependency> 
  3.     <groupId>com.alibaba.csp</groupId> 
  4.     <artifactId>sentinel-core</artifactId> 
  5.     <version>1.7.1</version> 
  6. </dependency> 

第二步:controller

  1. @RestController 
  2. @Slf4j 
  3. public class HelloWorldSentinelController { 
  4.  
  5.     @Autowired 
  6.     private BusiServiceImpl busiService; 
  7.  
  8.     /** 
  9.      * 初始化流控规则 
  10.      */ 
  11.     @PostConstruct 
  12.     public void init() { 
  13.  
  14.         List<FlowRule> flowRules = new ArrayList<>(); 
  15.  
  16.         /** 
  17.          * 定义 helloSentinelV1 受保护的资源的规则 
  18.          */ 
  19.         //创建流控规则对象 
  20.         FlowRule flowRule = new FlowRule(); 
  21.         //设置流控规则 QPS 
  22.         flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS); 
  23.         //设置受保护的资源 
  24.         flowRule.setResource("helloSentinelV1"); 
  25.         //设置受保护的资源的阈值 
  26.         flowRule.setCount(1); 
  27.  
  28.         flowRules.add(flowRule); 
  29.  
  30.         //加载配置好的规则 
  31.         FlowRuleManager.loadRules(flowRules); 
  32.     } 
  33.  
  34.  
  35.     /** 
  36.      * 频繁请求接口 http://localhost:8080/helloSentinelV1 
  37.      * 这种做法的缺点: 
  38.      * 1)业务侵入性很大,需要在你的controoler中写入 非业务代码.. 
  39.      * 2)配置不灵活 若需要添加新的受保护资源 需要手动添加 init方法来添加流控规则 
  40.      * @return 
  41.      */ 
  42.     @RequestMapping("/helloSentinelV1"
  43.     public String testHelloSentinelV1() { 
  44.  
  45.         Entry entity =null
  46.         //关联受保护的资源 
  47.         try { 
  48.             entity = SphU.entry("helloSentinelV1"); 
  49.             //开始执行 自己的业务方法 
  50.             busiService.doBusi(); 
  51.             //结束执行自己的业务方法 
  52.         } catch (BlockException e) { 
  53.             log.info("testHelloSentinelV1方法被流控了"); 
  54.             return "testHelloSentinelV1方法被流控了"
  55.         }finally { 
  56.             if(entity!=null) { 
  57.                 entity.exit(); 
  58.             } 
  59.         } 
  60.         return "OK"
  61.     } 

测试效果:

http://localhost:8080/helloSentinelV1

V1版本的缺陷如下:

  • 业务侵入性很大,需要在你的controoler中写入 非业务代码.
  • 配置不灵活 若需要添加新的受保护资源 需要手动添加 init方法来添加流控规则

V2版本:基于V1版本,再添加一个依赖

  1. <dependency> 
  2.     <groupId>com.alibaba.csp</groupId> 
  3.     <artifactId>sentinel-annotation-aspectj</artifactId> 
  4.     <version>1.7.1</version> 
  5. </dependency> 

编写controller

  1. // 配置一个切面 
  2. @Configuration 
  3. public class SentinelConfig { 
  4.  
  5.     @Bean 
  6.     public SentinelResourceAspect sentinelResourceAspect() { 
  7.         return new SentinelResourceAspect(); 
  8.     } 
  9.  
  10.  
  11. /** 
  12.  * 初始化流控规则 
  13.  */ 
  14. @PostConstruct 
  15. public void init() { 
  16.  
  17.     List<FlowRule> flowRules = new ArrayList<>(); 
  18.  
  19.     /** 
  20.      * 定义 helloSentinelV2 受保护的资源的规则 
  21.      */ 
  22.     //创建流控规则对象 
  23.     FlowRule flowRule2 = new FlowRule(); 
  24.     //设置流控规则 QPS 
  25.     flowRule2.setGrade(RuleConstant.FLOW_GRADE_QPS); 
  26.     //设置受保护的资源 
  27.     flowRule2.setResource("helloSentinelV2"); 
  28.     //设置受保护的资源的阈值 
  29.     flowRule2.setCount(1); 
  30.  
  31.     flowRules.add(flowRule2); 
  32.  
  33. /** 
  34.  * 频繁请求接口 http://localhost:8080/helloSentinelV2 
  35.  * 优点: 需要配置aspectj的切面SentinelResourceAspect ,添加注解@SentinelResource 
  36.  *     解决了v1版本中 sentinel的业务侵入代码问题,通过blockHandler指定被流控后调用的方法. 
  37.  * 缺点: 若我们的controller中的方法逐步变多,那么受保护的方法也越来越多,会导致一个问题 
  38.  * blockHandler的方法也会越来越多   引起方法急剧膨胀 怎么解决 
  39.  * 
  40.  * 注意点: 
  41.  *   blockHandler 对应处理 BlockException 的函数名称, 
  42.  *   可选项。blockHandler 函数访问范围需要是 public,返回类型需要与原方法相匹配, 
  43.  *   参数类型需要和原方法相匹配并且最后加一个额外的参数, 
  44.  *   类型为 BlockException。blockHandler 函数默认需要和原方法在同一个类中 
  45.  * @return 
  46.  */ 
  47. @RequestMapping("/helloSentinelV2"
  48. @SentinelResource(value = "helloSentinelV2",blockHandler ="testHelloSentinelV2BlockMethod"
  49. public String testHelloSentinelV2() { 
  50.     busiService.doBusi(); 
  51.     return "OK"
  52.  
  53. public String testHelloSentinelV2BlockMethod(BlockException e) { 
  54.     log.info("testRt流控"); 
  55.     return "testRt降级 流控...."+e; 

测试效果:

http://localhost:8080/helloSentinelV2

V3版本 基于V2缺点改进

  1. /** 
  2.  * 初始化流控规则 
  3.  */ 
  4. @PostConstruct 
  5. public void init() { 
  6.  
  7.     List<FlowRule> flowRules = new ArrayList<>(); 
  8.  
  9.     /** 
  10.      * 定义 helloSentinelV3 受保护的资源的规则 
  11.      */ 
  12.     //创建流控规则对象 
  13.     FlowRule flowRule3 = new FlowRule(); 
  14.     //设置流控规则 QPS 
  15.     flowRule3.setGrade(RuleConstant.FLOW_GRADE_QPS); 
  16.     //设置受保护的资源 
  17.     flowRule3.setResource("helloSentinelV3"); 
  18.     //设置受保护的资源的阈值 
  19.     flowRule3.setCount(1); 
  20.  
  21.  
  22.  
  23.     flowRules.add(flowRule3); 
  24.  
  25. /** 
  26.  * 我们看到了v2中的缺点,我们通过blockHandlerClass 来指定处理被流控的类 
  27.  * 通过testHelloSentinelV3BlockMethod 来指定blockHandlerClass 中的方法名称 
  28.  * ***这种方式 处理异常流控的方法必须要是static的 
  29.  * 频繁请求接口 http://localhost:8080/helloSentinelV3 
  30.  * @return 
  31.  */ 
  32. @RequestMapping("/helloSentinelV3"
  33. @SentinelResource(value = "helloSentinelV3",blockHandler = "testHelloSentinelV3BlockMethod",blockHandlerClass = BlockUtils.class) 
  34. public String testHelloSentinelV3() { 
  35.     busiService.doBusi(); 
  36.     return "OK"
  37.  
  38. // 异常处理类 
  39. @Slf4j 
  40. public class BlockUtils { 
  41.  
  42.  
  43.     public static String testHelloSentinelV3BlockMethod(BlockException e){ 
  44.         log.info("testHelloSentinelV3方法被流控了"); 
  45.         return "testHelloSentinelV3方法被流控了"
  46.     } 

测试效果:

http://localhost:8080/helloSentinelV3


缺点:不能动态的添加规则。如何解决问题?

3.2 如何在工程中快速整合Sentinel

  1. <!--加入sentinel--> 
  2. <dependency> 
  3.     <groupId>com.alibaba.cloud</groupId> 
  4.     <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> 
  5. </dependency> 
  6.  
  7.  
  8. <!--加入actuator--> 
  9. <dependency> 
  10.     <groupId>org.springframework.boot</groupId> 
  11.     <artifactId>spring-boot-starter-actuator</artifactId> 
  12. </dependency> 

添加Sentinel后,会暴露/actuator/sentinel 端点http://localhost:8080/actuator/sentinel

而Springboot默认是没有暴露该端点的,所以我们需要自己配置

  1. server: 
  2.   port: 8080 
  3. management: 
  4.   endpoints: 
  5.     web: 
  6.       exposure: 
  7.         include: '*' 

 

3.3 我们需要整合Sentinel-dashboard(哨兵流量卫兵)

下载地址:

https://github.com/alibaba/Sentinel/releases (我这里版本是:1.6.3)

  • 第一步:执行 java -jar sentinel-dashboard-1.6.3.jar 启动(就是一个SpringBoot工程)
  • 第二步:访问我们的sentinel控制台(1.6版本加入登陆页面)http://localhost:8080/ ,默认账户密码:sentinel/sentinel

  • 第三步:我们的微服务 niuh04-ms-alibaba-sentinel-order 整合 sentinel,我们也搭建好了Sentinel控制台,为微服务添加sentinel的控制台地址
  1. spring: 
  2.   cloud: 
  3.     sentinel: 
  4.       transport: 
  5.         dashboard: localhost:9999 

 四、Sentinel监控性能指标详解

4.1 实时监控面板

在这个面板中我们监控我们接口的 通过的QPS 和 拒绝的QPS,在没有设置流控规则,我们是看不到拒绝的QPS。

4.2 簇点链路

用来线上微服务的所监控的API

4.3 流控设置

簇点链路 选择具体的访问的API,然后点击“流控按钮”

含义:

资源名:为我们接口的API /selectOrderInfoById/1

针对来源:这里是默认的 default(标识不针对来源),还有一种情况就是假设微服务A需要调用这个资源,微服务B也需要调用这个资源,那么我们就可以单独的为微服务A和微服务B进行设置阀值。

阀值类型:分为QPS和线程数,假设阀值为2

QPS类型:指的是每秒钟访问接口的次数 > 2 就进行限流

线程数:为接受请求该资源,分配的线程数 > 2 就进行限流

流控模式

1.直接:这种很好理解,就是达到设置的阀值后直接被流控抛出异常

疯狂的请求这个路径

2.关联

业务场景:我们现在有两个API,第一个是保存订单,一个是查询订单,假设我们希望有限操作“保存订单”

测试:写两个读写测试接口

  1. /** 
  2.  * 方法实现说明:模仿  流控模式【关联】  读接口 
  3.  * @author:hejianhui 
  4.  * @param orderNo 
  5.  * @return
  6.  * @exception: 
  7.  * @date:2019/11/24 22:06 
  8.  */ 
  9. @RequestMapping("/findById/{orderNo}"
  10. public Object findById(@PathVariable("orderNo") String orderNo) { 
  11.     log.info("orderNo:{}","执行查询操作"+System.currentTimeMillis()); 
  12.     return orderInfoMapper.selectOrderInfoById(orderNo); 
  13.  
  14.  
  15. /** 
  16.  * 方法实现说明:模仿流控模式【关联】   写接口(优先) 
  17.  * @author:hejianhui 
  18.  * @return
  19.  * @exception: 
  20.  * @date:2019/11/24 22:07 
  21.  */ 
  22. @RequestMapping("/saveOrder"
  23. public String saveOrder() throws InterruptedException { 
  24.     //Thread.sleep(500); 
  25.     log.info("执行保存操作,模仿返回订单ID"); 
  26.     return UUID.randomUUID().toString(); 

测试代码:写一个for循环一直调用我们的写接口,让写接口QPS达到阀值

  1. public class TestSentinelRule { 
  2.  
  3.     public static void main(String[] args) throws InterruptedException { 
  4.         RestTemplate restTemplate = new RestTemplate(); 
  5.         for(int i=0;i<1000;i++) { 
  6.             restTemplate.postForObject("http://localhost:8080/saveOrder",null,String.class); 
  7.             Thread.sleep(10); 
  8.         } 
  9.     } 

此时访问我们的读接口:此时被限流了。

3.链路

用法说明,本地实验没成功,用alibaba 未毕业版本0.9.0可以测试出效果,API级别的限制流量

代码:

  1. @RequestMapping("/findAll"
  2. public String findAll() throws InterruptedException { 
  3.     orderServiceImpl.common(); 
  4.     return "findAll"
  5.  
  6. @RequestMapping("/findAllByCondtion"
  7. public String findAllByCondtion() { 
  8.     orderServiceImpl.common(); 
  9.     return "findAllByCondition"
  10.  
  11. @Service 
  12. public class OrderServiceImpl { 
  13.  
  14.     @SentinelResource("common"
  15.     public String common() { 
  16.         return "common"
  17.     } 

根据流控规则来说: 只会限制/findAll的请求,不会限制/findAllByCondtion规则

流控效果

1.快速失败(直接抛出异常)每秒的QPS 操作过1 就直接抛出异常

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

2.预热(warmUp)源码:com.alibaba.csp.sentinel.slots.block.flow.controller.WarmUpController>

当流量突然增大的时候,我们常常会希望系统从空闲状态到繁忙状态的切换的时间长一些。即如果系统在此之前长期处于空闲的状态,我们希望处理请求的数量是缓步增加,经过预期的时间后,到达系统处理请求个数的最大值。Warm Up (冷启动,预热)模式就是为了实现这个目的。

冷加载因子:codeFacotr 默认是3

默认 coldFactor 为3,即请求 QPS 从 threshold / 3 开始,经预热时长逐渐升至设定的 QPS 阀值。

上图设置:就是QPS从100/3=33开始算, 经过10秒钟,达到一百的QPS 才进行限制流量。

详情文档:

https://github.com/alibaba/Sentinel/wiki/限流---冷启动

排队等待源码:com.alibaba.csp.sentinel.slots.block.flow.controller.RateLimiterController

这种方式适合用于请求以突刺状来到,这个时候我们不希望一下子把所有的请求都通过,这样可能会把系统压垮;同时我们也期待系统以稳定的速度,逐步处理这些请求,以起到“削峰填谷”的效果,而不是拒绝所有请求。

选择排队等待的阀值类型必须是****QPS

上图设置:单机阀值为10,表示每秒通过的请求个数是10,也就是每个请求平均间隔恒定为 1000 / 10 = 100 ms,每一个请求的最长等待时间(maxQueueingTimeMs)为 20 * 1000ms = 20s。,超过20s就丢弃请求。

  • 详情文档:
  • https://github.com/alibaba/Sentinel/wiki/流量控制-匀速排队模式

4.4 降级规则

rt(平均响应时间)

平均响应时间(DEGRADE_GRADE_RT):当 1s 内持续进入5个请求,对应时刻的平均响应时间(秒级)均超过阀值(count,以 ms 为单位),那么在接下来的时间窗口(DegradeRule 中的 timeWindow,以 s 为单位)之内,对这个方法的调用都会自动地熔断(抛出 DegradeException)。

注意:Sentinel 默认同级的 RT 上限是4900ms,超出此阀值都会算做4900ms,若需要变更此上限可以通过启动配置项:-Dcsp.sentinel.statistic.max.rt=xxx 来配置

异常比例(DEGRADE_GRADE_EXCEPTION_RATIO)

当资源的每秒请求量 >= 5,并且每秒异常总数占通过量的比值超过阀值(DegradeRule 中的 count)之后,资源进入降级状态,即在接下的时间窗口(DegradeRule 中的 timeWindow,以 s 为单位)之内,对这个方法的调用都会自动地返回。异常比例的阀值范围是 [0.0, 1.0],代表 0% ~ 100% 。

异常数(DEGRADE_GRADE_EXCEPTION_COUNT)

当资源近千分之的异常数目超过阀值之后会进行熔断。注意由于统计时间窗口是分钟级别的,若 timeWindow 小于 60s,则结束熔断状态后仍可能再进入熔断状态。

4.5 热点参数

业务场景:秒杀业务,比如商场做促销秒杀,针对苹果11(商品id=1)进行9.9秒杀活动,那么这个时候,我们去请求订单接口(商品id=1)的请求流量十分大,我们就可以通过热点参数规则来控制 商品id=1 的请求的并发量。而其他正常商品的请求不会受到限制。那么这种热点参数规则使用。

五、Sentinel-dashboard 控制台 和 我们的微服务通信原理

5.1 控制台如何获取到微服务的监控信息?

5.2 在控制台配置规则,如何把规则推送给微服务的?

我们通过观察到sentinel-dashboard的机器列表上观察注册服务微服务信息。我们的 控制台就可以通过这些微服务的注册信息跟我们的具体的微服务进行通信.

 

5.3 微服务整合sentinel时候的提供的一些接口API地址: http://localhost:8720/api

5.4 我们可以通过代码设置规则(我们这里用流控规则为例)

  1. @RestController 
  2. public class AddFlowLimitController { 
  3.  
  4.     @RequestMapping("/addFlowLimit"
  5.     public String addFlowLimit() { 
  6.         List<FlowRule> flowRuleList = new ArrayList<>(); 
  7.  
  8.         FlowRule flowRule = new FlowRule("/testAddFlowLimitRule"); 
  9.  
  10.         //设置QPS阈值 
  11.         flowRule.setCount(1); 
  12.  
  13.         //设置流控模型为QPS模型 
  14.         flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS); 
  15.  
  16.         flowRuleList.add(flowRule); 
  17.  
  18.         FlowRuleManager.loadRules(flowRuleList); 
  19.  
  20.         return "success"
  21.  
  22.     } 
  23.  
  24.     @RequestMapping("/testAddFlowLimitRule"
  25.     public String testAddFlowLimitRule() { 
  26.         return "testAddFlowLimitRule"
  27.     } 

添加效果截图: 执行:

http://localhost:8080/addFlowLimit

Sentinel具体配置项:

https://github.com/alibaba/Sentinel/wiki/启动配置项

5.5 对SpringMVC端点保护关闭(一般应用场景是做压测需要关闭)

  1. spring: 
  2.   cloud: 
  3.     nacos: 
  4.       discovery: 
  5.         server-addr: localhost:8848 
  6.     sentinel: 
  7.       transport: 
  8.         dashboard: localhost:9999 
  9.       filter: 
  10.         enabled: true  #关闭Spring mvc的端点保护 

那么我们的这种类型的接口 不会被sentinel保护


只有加了 @SentinelResource 的注解的资源才会被保护

六、Ribbon整合Sentinel

6.1 第一步:加配置

  1. <!--加入ribbon--> 
  2. <dependency> 
  3.     <groupId>org.springframework.cloud</groupId> 
  4.     <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> 
  5. </dependency> 
  6.  
  7. <!--加入sentinel--> 
  8. <dependency> 
  9.     <groupId>com.alibaba.cloud</groupId> 
  10.     <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> 
  11. </dependency> 
  12.  
  13.  
  14. <!--加入actuator--> 
  15. <dependency> 
  16.     <groupId>org.springframework.boot</groupId> 
  17.     <artifactId>spring-boot-starter-actuator</artifactId> 
  18. </dependency> 

 6.2 第二步:加注解

在我们的RestTemplate组件上添加@SentinelRestTemplate注解。并且我们可以通过在@SentinelRestTemplate 同样的可以指定我们的 blockHandlerClass、fallbackClass、blockHandler、fallback 这四个属性

  1. @Configuration 
  2. public class WebConfig { 
  3.  
  4.     @Bean 
  5.     @LoadBalanced 
  6.     @SentinelRestTemplate( 
  7.             blockHandler = "handleException",blockHandlerClass = GlobalExceptionHandler.class, 
  8.             fallback = "fallback",fallbackClass = GlobalExceptionHandler.class 
  9.  
  10.     ) 
  11.     public RestTemplate restTemplate() { 
  12.         return new RestTemplate(); 
  13.     } 
  14.  
  15. *****************全局异常处理类***************** 
  16. @Slf4j 
  17. public class GlobalExceptionHandler { 
  18.  
  19.  
  20.     /** 
  21.      * 限流后处理方法 
  22.      * @param request 
  23.      * @param body 
  24.      * @param execution 
  25.      * @param ex 
  26.      * @return 
  27.      */ 
  28.     public static SentinelClientHttpResponse handleException(HttpRequest request, 
  29.                                                              byte[] body, ClientHttpRequestExecution execution, BlockException ex)  { 
  30.  
  31.         ProductInfo productInfo = new ProductInfo(); 
  32.         productInfo.setProductName("被限制流量拉"); 
  33.         productInfo.setProductNo("-1"); 
  34.         ObjectMapper objectMapper = new ObjectMapper(); 
  35.  
  36.         try { 
  37.             return new SentinelClientHttpResponse(objectMapper.writeValueAsString(productInfo)); 
  38.         } catch (JsonProcessingException e) { 
  39.             e.printStackTrace(); 
  40.             return null
  41.         } 
  42.     } 
  43.  
  44.     /** 
  45.      * 熔断后处理的方法 
  46.      * @param request 
  47.      * @param body 
  48.      * @param execution 
  49.      * @param ex 
  50.      * @return 
  51.      */ 
  52.     public static SentinelClientHttpResponse fallback(HttpRequest request, 
  53.                                                       byte[] body, ClientHttpRequestExecution execution, BlockException ex) { 
  54.         ProductInfo productInfo = new ProductInfo(); 
  55.         productInfo.setProductName("被降级拉"); 
  56.         productInfo.setProductNo("-1"); 
  57.         ObjectMapper objectMapper = new ObjectMapper(); 
  58.  
  59.         try { 
  60.             return new SentinelClientHttpResponse(objectMapper.writeValueAsString(productInfo)); 
  61.         } catch (JsonProcessingException e) { 
  62.             e.printStackTrace(); 
  63.             return null
  64.         } 
  65.     } 

 6.3 第三步:添加配置

什么时候关闭:一般在我们的自己测试业务功能是否正常的情况,关闭该配置

  1. #是否开启@SentinelRestTemplate注解 
  2. resttemplate: 
  3.   sentinel: 
  4.     enabled: true 

 七、OpenFeign整合我们的Sentinel

7.1 第一步:加配置

在niuh05-ms-alibaba-feignwithsentinel-order上 pom.xml中添加配置

  1. <!--加入sentinel--> 
  2. <dependency> 
  3.     <groupId>com.alibaba.cloud</groupId> 
  4.     <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> 
  5. </dependency> 
  6.  
  7.  
  8. <!--加入actuator--> 
  9. <dependency> 
  10.     <groupId>org.springframework.boot</groupId> 
  11.     <artifactId>spring-boot-starter-actuator</artifactId> 
  12. </dependency> 
  13.  
  14. <dependency> 
  15.     <groupId>com.niuh</groupId> 
  16.     <artifactId>niuh03-ms-alibaba-feign-api</artifactId> 
  17.     <version>0.0.1-SNAPSHOT</version> 
  18. </dependency> 

 7.2 第二步:在Feign的声明式接口上添加fallback属性或者 fallbackFactory属性

为我们添加fallback属性的api

  1. @FeignClient(name = "product-center",fallback = ProductCenterFeignApiWithSentinelFallback.class) 
  2. public interface ProductCenterFeignApiWithSentinel { 
  3.  
  4.     /** 
  5.      * 声明式接口,远程调用http://product-center/selectProductInfoById/{productNo} 
  6.      * @param productNo 
  7.      * @return 
  8.      */ 
  9.     @RequestMapping("/selectProductInfoById/{productNo}"
  10.     ProductInfo selectProductInfoById(@PathVariable("productNo") String productNo) throws InterruptedException; 

我们feign的限流降级接口(通过fallback没有办法获取到异常的)

  1. @Component 
  2. public class ProductCenterFeignApiWithSentinelFallback implements ProductCenterFeignApiWithSentinel { 
  3.     @Override 
  4.     public ProductInfo selectProductInfoById(String productNo) { 
  5.         ProductInfo productInfo = new ProductInfo(); 
  6.         productInfo.setProductName("默认商品"); 
  7.         return productInfo; 
  8.     } 

为我们添加fallbackFactory属性的api

  1. package com.niuh.feignapi.sentinel; 
  2.  
  3. import com.niuh.entity.ProductInfo; 
  4. import com.niuh.handler.ProductCenterFeignApiWithSentielFallbackFactoryasdasf; 
  5. import com.niuh.handler.ProductCenterFeignApiWithSentinelFallback; 
  6. import org.springframework.cloud.openfeign.FeignClient; 
  7. import org.springframework.web.bind.annotation.PathVariable; 
  8. import org.springframework.web.bind.annotation.RequestMapping; 
  9.  
  10. /** 
  11.  * Created by hejianhui on 2019/11/22. 
  12.  */ 
  13.  
  14. @FeignClient(name = "product-center",fallbackFactory = ProductCenterFeignApiWithSentielFallbackFactoryasdasf.class) 
  15. public interface ProductCenterFeignApiWithSentinel { 
  16.  
  17.     /** 
  18.      * 声明式接口,远程调用http://product-center/selectProductInfoById/{productNo} 
  19.      * @param productNo 
  20.      * @return 
  21.      */ 
  22.     @RequestMapping("/selectProductInfoById/{productNo}"
  23.     ProductInfo selectProductInfoById(@PathVariable("productNo") String productNo) throws InterruptedException; 

通过FallbackFactory属性可以处理我们的异常

  1. @Component 
  2. @Slf4j 
  3. public class ProductCenterFeignApiWithSentielFallbackFactoryasdasf implements FallbackFactory<ProductCenterFeignApiWithSentinel> { 
  4.     @Override 
  5.     public ProductCenterFeignApiWithSentinel create(Throwable throwable) { 
  6.         return new ProductCenterFeignApiWithSentinel(){ 
  7.  
  8.             @Override 
  9.             public ProductInfo selectProductInfoById(String productNo) { 
  10.                 ProductInfo productInfo = new ProductInfo(); 
  11.                 if (throwable instanceof FlowException) { 
  12.                     log.error("流控了....{}",throwable.getMessage()); 
  13.                     productInfo.setProductName("我是被流控的默认商品"); 
  14.                 }else { 
  15.                     log.error("降级了....{}",throwable.getMessage()); 
  16.                     productInfo.setProductName("我是被降级的默认商品"); 
  17.                 } 
  18.  
  19.                 return productInfo; 
  20.             } 
  21.         }; 
  22.     } 

 八、Sentinel 规则持久化

Sentinel-dashboard 配置的规则,在我们的微服务以及控制台重启的时候就清空了,因为它是基于内存的。

8.1 原生模式

Dashboard 的推送规则方式是通过 API 将规则推送至客户端并直接更新到内存。

优缺点:这种做法的好处是简单,无依赖;坏处是应用重启规则就会消失,仅用于简单测试,不能用于生产环境。

8.2 Pull拉模式

首先 Sentinel 控制台通过 API 将规则推送至客户端并更新到内存中,接着注册的写数据源会将新的规则保存到本地的文件中。使用 pull 模式的数据源时一般不需要对 Sentinel 控制台进行改造。

这种实现方法好处是简单,不引入新的依赖,坏处是无法保证监控数据的一致性

客户端Sentinel的改造(拉模式)

通过SPI扩展机制进行扩展,我们写一个拉模式的实现类

com.niuh.persistence.PullModeByFileDataSource ,然后在工厂目录下创建

META-INF/services/com.alibaba.csp.sentinel.init.InitFun文件。


文件的内容就是写我们的拉模式的实现类:

  • 代码在
  • niuh05-ms-alibaba-sentinelrulepersistencepull-order 工程的persistence包下。

8.3 Push推模式(以Nacos为例,生产推荐使用)

原理简述

  • 控制台推送规则:
  • 将规则推送至Nacos获取其他远程配置中心
  • Sentinel客户端连接Nacos,获取规则配置;并监听Nacos配置变化,如果发送变化,就更新本地缓存(从而让本地缓存总是和Nacos一致)
  • 控制台监听Nacos配置变化,如果发送变化就更新本地缓存(从而让控制台本地缓存和Nacos一致)

改造方案

微服务改造方案

第一步:在niuh05-ms-alibaba-sentinelrulepersistencepush-order工程加入依赖

  1. <dependency> 
  2.     <groupId>com.alibaba.csp</groupId> 
  3.     <artifactId>sentinel-datasource-nacos</artifactId> 
  4. </dependency> 

第二步:加入yml的配置

  1. spring: 
  2.   cloud: 
  3.     nacos: 
  4.       discovery: 
  5.         server-addr: localhost:8848 
  6.     sentinel: 
  7.       transport: 
  8.         dashboard: localhost:9999 
  9.         #namespace: bc7613d2-2e22-4292-a748-48b78170f14c  #指定namespace的id 
  10.       datasource: 
  11.         # 名称随意 
  12.         flow: 
  13.           nacos: 
  14.             server-addr: 47.111.191.111:8848 
  15.             dataId: ${spring.application.name}-flow-rules 
  16.             groupId: SENTINEL_GROUP 
  17.             rule-type: flow 
  18.         degrade: 
  19.           nacos: 
  20.             server-addr: localhost:8848 
  21.             dataId: ${spring.application.name}-degrade-rules 
  22.             groupId: SENTINEL_GROUP 
  23.             rule-type: degrade 
  24.         system: 
  25.           nacos: 
  26.             server-addr: localhost:8848 
  27.             dataId: ${spring.application.name}-system-rules 
  28.             groupId: SENTINEL_GROUP 
  29.             rule-type: system 
  30.         authority: 
  31.           nacos: 
  32.             server-addr: localhost:8848 
  33.             dataId: ${spring.application.name}-authority-rules 
  34.             groupId: SENTINEL_GROUP 
  35.             rule-type: authority 
  36.         param-flow: 
  37.           nacos: 
  38.             server-addr: localhost:8848 
  39.             dataId: ${spring.application.name}-param-flow-rules 
  40.             groupId: SENTINEL_GROUP 
  41.             rule-type: param-flow 

Sentinel-dashboard改造方案

  1. <!-- for Nacos rule publisher sample --> 
  2. <dependency> 
  3.     <groupId>com.alibaba.csp</groupId> 
  4.     <artifactId>sentinel-datasource-nacos</artifactId> 
  5.    <!-- <scope>test</scope>--> // 需要把test注释掉 
  6. </dependency> 

控制台改造主要是为规则实现:

  • DynamicRuleProvider :从Nacos上读取配置
  • DynamicRulePublisher :将规则推送到Nacis上

在sentinel-dashboard工程目录

com.alibaba.csp.sentinel.dashboard.rule 下创建一 个Nacos的包,然后把我们的各个场景的配置规则类写到该包下.

我们以ParamFlowRuleController(热点参数流控类作为修改作为演示)

  1. /** 
  2.  * @author Eric Zhao 
  3.  * @since 0.2.1 
  4.  */ 
  5. @RestController 
  6. @RequestMapping(value = "/paramFlow"
  7. public class ParamFlowRuleController { 
  8.  
  9.     private final Logger logger = LoggerFactory.getLogger(ParamFlowRuleController.class); 
  10.  
  11.     @Autowired 
  12.     private SentinelApiClient sentinelApiClient; 
  13.     @Autowired 
  14.     private AppManagement appManagement; 
  15.     @Autowired 
  16.     private RuleRepository<ParamFlowRuleEntity, Long> repository; 
  17.  
  18.     @Autowired 
  19.     @Qualifier("niuhHotParamFlowRuleNacosPublisher"
  20.     private DynamicRulePublisher<List<ParamFlowRuleEntity>> rulePublisher; 
  21.  
  22.     @Autowired 
  23.     @Qualifier("niuhHotParamFlowRuleNacosProvider"
  24.     private DynamicRuleProvider<List<ParamFlowRuleEntity>> ruleProvider; 
  25.  
  26.     @Autowired 
  27.     private AuthService<HttpServletRequest> authService; 
  28.  
  29.     private boolean checkIfSupported(String app, String ip, int port) { 
  30.         try { 
  31.             return Optional.ofNullable(appManagement.getDetailApp(app)) 
  32.                 .flatMap(e -> e.getMachine(ip, port)) 
  33.                 .flatMap(m -> VersionUtils.parseVersion(m.getVersion()) 
  34.                     .map(v -> v.greaterOrEqual(version020))) 
  35.                 .orElse(true); 
  36.             // If error occurred or cannot retrieve machine info, return true
  37.         } catch (Exception ex) { 
  38.             return true
  39.         } 
  40.     } 
  41.  
  42.     @GetMapping("/rules"
  43.     public Result<List<ParamFlowRuleEntity>> apiQueryAllRulesForMachine(HttpServletRequest request, 
  44.                                                                         @RequestParam String app, 
  45.                                                                         @RequestParam String ip, 
  46.                                                                         @RequestParam Integer port) { 
  47.         AuthUser authUser = authService.getAuthUser(request); 
  48.         authUser.authTarget(app, PrivilegeType.READ_RULE); 
  49.         if (StringUtil.isEmpty(app)) { 
  50.             return Result.ofFail(-1, "app cannot be null or empty"); 
  51.         } 
  52.         if (StringUtil.isEmpty(ip)) { 
  53.             return Result.ofFail(-1, "ip cannot be null or empty"); 
  54.         } 
  55.         if (port == null || port <= 0) { 
  56.             return Result.ofFail(-1, "Invalid parameter: port"); 
  57.         } 
  58.         if (!checkIfSupported(app, ip, port)) { 
  59.             return unsupportedVersion(); 
  60.         } 
  61.         try { 
  62. /*            return sentinelApiClient.fetchParamFlowRulesOfMachine(app, ip, port) 
  63.                 .thenApply(repository::saveAll) 
  64.                 .thenApply(Result::ofSuccess) 
  65.                 .get();*/ 
  66.             List<ParamFlowRuleEntity> rules = ruleProvider.getRules(app); 
  67.             rules = repository.saveAll(rules); 
  68.             return Result.ofSuccess(rules); 
  69.         } catch (ExecutionException ex) { 
  70.             logger.error("Error when querying parameter flow rules", ex.getCause()); 
  71.             if (isNotSupported(ex.getCause())) { 
  72.                 return unsupportedVersion(); 
  73.             } else { 
  74.                 return Result.ofThrowable(-1, ex.getCause()); 
  75.             } 
  76.         } catch (Throwable throwable) { 
  77.             logger.error("Error when querying parameter flow rules", throwable); 
  78.             return Result.ofFail(-1, throwable.getMessage()); 
  79.         } 
  80.     } 
  81.  
  82.     private boolean isNotSupported(Throwable ex) { 
  83.         return ex instanceof CommandNotFoundException; 
  84.     } 
  85.  
  86.     @PostMapping("/rule"
  87.     public Result<ParamFlowRuleEntity> apiAddParamFlowRule(HttpServletRequest request, 
  88.                                                            @RequestBody ParamFlowRuleEntity entity) { 
  89.         AuthUser authUser = authService.getAuthUser(request); 
  90.         authUser.authTarget(entity.getApp(), PrivilegeType.WRITE_RULE); 
  91.         Result<ParamFlowRuleEntity> checkResult = checkEntityInternal(entity); 
  92.         if (checkResult != null) { 
  93.             return checkResult; 
  94.         } 
  95.         if (!checkIfSupported(entity.getApp(), entity.getIp(), entity.getPort())) { 
  96.             return unsupportedVersion(); 
  97.         } 
  98.         entity.setId(null); 
  99.         entity.getRule().setResource(entity.getResource().trim()); 
  100.         Date date = new Date(); 
  101.         entity.setGmtCreate(date); 
  102.         entity.setGmtModified(date); 
  103.         try { 
  104.             entity = repository.save(entity); 
  105.             //publishRules(entity.getApp(), entity.getIp(), entity.getPort()).get(); 
  106.             publishRules(entity.getApp()); 
  107.             return Result.ofSuccess(entity); 
  108.         } catch (ExecutionException ex) { 
  109.             logger.error("Error when adding new parameter flow rules", ex.getCause()); 
  110.             if (isNotSupported(ex.getCause())) { 
  111.                 return unsupportedVersion(); 
  112.             } else { 
  113.                 return Result.ofThrowable(-1, ex.getCause()); 
  114.             } 
  115.         } catch (Throwable throwable) { 
  116.             logger.error("Error when adding new parameter flow rules", throwable); 
  117.             return Result.ofFail(-1, throwable.getMessage()); 
  118.         } 
  119.     } 
  120.  
  121.     private <R> Result<R> checkEntityInternal(ParamFlowRuleEntity entity) { 
  122.         if (entity == null) { 
  123.             return Result.ofFail(-1, "bad rule body"); 
  124.         } 
  125.         if (StringUtil.isBlank(entity.getApp())) { 
  126.             return Result.ofFail(-1, "app can't be null or empty"); 
  127.         } 
  128.         if (StringUtil.isBlank(entity.getIp())) { 
  129.             return Result.ofFail(-1, "ip can't be null or empty"); 
  130.         } 
  131.         if (entity.getPort() == null || entity.getPort() <= 0) { 
  132.             return Result.ofFail(-1, "port can't be null"); 
  133.         } 
  134.         if (entity.getRule() == null) { 
  135.             return Result.ofFail(-1, "rule can't be null"); 
  136.         } 
  137.         if (StringUtil.isBlank(entity.getResource())) { 
  138.             return Result.ofFail(-1, "resource name cannot be null or empty"); 
  139.         } 
  140.         if (entity.getCount() < 0) { 
  141.             return Result.ofFail(-1, "count should be valid"); 
  142.         } 
  143.         if (entity.getGrade() != RuleConstant.FLOW_GRADE_QPS) { 
  144.             return Result.ofFail(-1, "Unknown mode (blockGrade) for parameter flow control"); 
  145.         } 
  146.         if (entity.getParamIdx() == null || entity.getParamIdx() < 0) { 
  147.             return Result.ofFail(-1, "paramIdx should be valid"); 
  148.         } 
  149.         if (entity.getDurationInSec() <= 0) { 
  150.             return Result.ofFail(-1, "durationInSec should be valid"); 
  151.         } 
  152.         if (entity.getControlBehavior() < 0) { 
  153.             return Result.ofFail(-1, "controlBehavior should be valid"); 
  154.         } 
  155.         return null
  156.     } 
  157.  
  158.     @PutMapping("/rule/{id}"
  159.     public Result<ParamFlowRuleEntity> apiUpdateParamFlowRule(HttpServletRequest request, 
  160.                                                               @PathVariable("id") Long id, 
  161.                                                               @RequestBody ParamFlowRuleEntity entity) { 
  162.         AuthUser authUser = authService.getAuthUser(request); 
  163.         if (id == null || id <= 0) { 
  164.             return Result.ofFail(-1, "Invalid id"); 
  165.         } 
  166.         ParamFlowRuleEntity oldEntity = repository.findById(id); 
  167.         if (oldEntity == null) { 
  168.             return Result.ofFail(-1, "id " + id + " does not exist"); 
  169.         } 
  170.         authUser.authTarget(oldEntity.getApp(), PrivilegeType.WRITE_RULE); 
  171.         Result<ParamFlowRuleEntity> checkResult = checkEntityInternal(entity); 
  172.         if (checkResult != null) { 
  173.             return checkResult; 
  174.         } 
  175.         if (!checkIfSupported(entity.getApp(), entity.getIp(), entity.getPort())) { 
  176.             return unsupportedVersion(); 
  177.         } 
  178.         entity.setId(id); 
  179.         Date date = new Date(); 
  180.         entity.setGmtCreate(oldEntity.getGmtCreate()); 
  181.         entity.setGmtModified(date); 
  182.         try { 
  183.             entity = repository.save(entity); 
  184.             //publishRules(entity.getApp(), entity.getIp(), entity.getPort()).get(); 
  185.             publishRules(entity.getApp()); 
  186.             return Result.ofSuccess(entity); 
  187.         } catch (ExecutionException ex) { 
  188.             logger.error("Error when updating parameter flow rules, id=" + id, ex.getCause()); 
  189.             if (isNotSupported(ex.getCause())) { 
  190.                 return unsupportedVersion(); 
  191.             } else { 
  192.                 return Result.ofThrowable(-1, ex.getCause()); 
  193.             } 
  194.         } catch (Throwable throwable) { 
  195.             logger.error("Error when updating parameter flow rules, id=" + id, throwable); 
  196.             return Result.ofFail(-1, throwable.getMessage()); 
  197.         } 
  198.     } 
  199.  
  200.     @DeleteMapping("/rule/{id}"
  201.     public Result<Long> apiDeleteRule(HttpServletRequest request, @PathVariable("id") Long id) { 
  202.         AuthUser authUser = authService.getAuthUser(request); 
  203.         if (id == null) { 
  204.             return Result.ofFail(-1, "id cannot be null"); 
  205.         } 
  206.         ParamFlowRuleEntity oldEntity = repository.findById(id); 
  207.         if (oldEntity == null) { 
  208.             return Result.ofSuccess(null); 
  209.         } 
  210.         authUser.authTarget(oldEntity.getApp(), PrivilegeType.DELETE_RULE); 
  211.         try { 
  212.             repository.delete(id); 
  213.             /*publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort()).get();*/ 
  214.             publishRules(oldEntity.getApp()); 
  215.             return Result.ofSuccess(id); 
  216.         } catch (ExecutionException ex) { 
  217.             logger.error("Error when deleting parameter flow rules", ex.getCause()); 
  218.             if (isNotSupported(ex.getCause())) { 
  219.                 return unsupportedVersion(); 
  220.             } else { 
  221.                 return Result.ofThrowable(-1, ex.getCause()); 
  222.             } 
  223.         } catch (Throwable throwable) { 
  224.             logger.error("Error when deleting parameter flow rules", throwable); 
  225.             return Result.ofFail(-1, throwable.getMessage()); 
  226.         } 
  227.     } 
  228.  
  229.     private CompletableFuture<Void> publishRules(String app, String ip, Integer port) { 
  230.         List<ParamFlowRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port)); 
  231.         return sentinelApiClient.setParamFlowRuleOfMachine(app, ip, port, rules); 
  232.     } 
  233.  
  234.     private void publishRules(String app) throws Exception { 
  235.         List<ParamFlowRuleEntity> rules = repository.findAllByApp(app); 
  236.         rulePublisher.publish(app, rules); 
  237.     } 
  238.  
  239.     private <R> Result<R> unsupportedVersion() { 
  240.         return Result.ofFail(4041, 
  241.             "Sentinel client not supported for parameter flow control (unsupported version or dependency absent)"); 
  242.     } 
  243.  
  244.     private final SentinelVersion version020 = new SentinelVersion().setMinorVersion(2); 

 8.4 阿里云的 AHAS

  • 开通地址:https://ahas.console.aliyun.com/
  • 开通规则说明:https://help.aliyun.com/document_detail/90323.html

第一步:访问

https://help.aliyun.com/document_detail/90323.html

第二步:免费开通

第三步开通

第四步:接入应用

第五步:点击接入SDK

第六步:加入我们的应用

以niuh05-ms-alibaba-sentinelrulepersistence-ahas-order工程为例

加入ahas的依赖

  1. <dependency> 
  2.     <groupId>com.alibaba.csp</groupId> 
  3.     <artifactId>spring‐boot‐starter‐ahas‐sentinel‐client</artifactId> 4 <version>1.5.0</version> 
  4. </dependency> 

加入配置:yml的配置

  1. ahas.namespace: default 
  2. project.nameorder-center 
  3. ahas.license: b833de8ab5f34e4686457ecb2b60fa46 

测试接口

  1. @SentinelResource("hot-param-flow-rule"
  2. @RequestMapping("/testHotParamFlowRule"
  3. public OrderInfo testHotParamFlowRule(@RequestParam("orderNo") String orderNo) { 
  4.     return orderInfoMapper.selectOrderInfoById(orderNo); 

第一次访问接口:

AHas控制台出现我们的微服务

添加我们直接的流控规则

疯狂刷新我们的测试接口:

九、Sentinel 线上环境的优化

9.1 优化错误页面

流控错误页面

降级错误页面

发现这两种错误都是医院,显然这里我们需要优化 UrlBlockHandler 提供了一个接口,我们需要实现这个接口

  1. /** 
  2. * @vlog: 高于生活,源于生活 
  3. * @desc: 类的描述:处理流控,降级规则 
  4. * @author: hejianhui 
  5. * @createDate: 2019/12/3 16:40 
  6. * @version: 1.0 
  7. */ 
  8. @Component 
  9. public class NiuhUrlBlockHandler implements UrlBlockHandler { 
  10.  
  11.     public static final Logger log = LoggerFactory.getLogger(NiuhUrlBlockHandler.class); 
  12.  
  13.     @Override 
  14.     public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException { 
  15.  
  16.         if(ex instanceof FlowException) { 
  17.             log.warn("触发了流控"); 
  18.             warrperResponse(response,ErrorEnum.FLOW_RULE_ERR); 
  19.         }else if(ex instanceof ParamFlowException) { 
  20.             log.warn("触发了参数流控"); 
  21.             warrperResponse(response,ErrorEnum.HOT_PARAM_FLOW_RULE_ERR); 
  22.         }else if(ex instanceof AuthorityException) { 
  23.             log.warn("触发了授权规则"); 
  24.             warrperResponse(response,ErrorEnum.AUTH_RULE_ERR); 
  25.         }else if(ex instanceof SystemBlockException) { 
  26.             log.warn("触发了系统规则"); 
  27.             warrperResponse(response,ErrorEnum.SYS_RULE_ERR); 
  28.         }else
  29.             log.warn("触发了降级规则"); 
  30.             warrperResponse(response,ErrorEnum.DEGRADE_RULE_ERR); 
  31.         } 
  32.     } 
  33.  
  34.  
  35.     private void warrperResponse(HttpServletResponse httpServletResponse, ErrorEnum errorEnum) throws IOException { 
  36.         httpServletResponse.setStatus(500); 
  37.         httpServletResponse.setCharacterEncoding("UTF-8"); 
  38.         httpServletResponse.setHeader("Content-Type","application/json;charset=utf-8"); 
  39.         httpServletResponse.setContentType("application/json;charset=utf-8"); 
  40.  
  41.         ObjectMapper objectMapper = new ObjectMapper(); 
  42.         String errMsg =objectMapper.writeValueAsString(new ErrorResult(errorEnum)); 
  43.         httpServletResponse.getWriter().write(errMsg); 
  44.     } 
  45.  

优化后:

流控规则提示:

降级规则提示:

9.2 针对来源编码实现

Sentinel 提供了一个 RequestOriginParser 接口,我们可以在这里实现编码从请求头中区分来源

  1. /** 
  2. * @vlog: 高于生活,源于生活 
  3. * @desc: 类的描述:区分来源接口 
  4. * @author: hejianhui 
  5. * @createDate: 2019/12/4 13:13 
  6. * @version: 1.0 
  7. */ 
  8. /*@Component*/ 
  9. @Slf4j 
  10. public class NiuhRequestOriginParse implements RequestOriginParser { 
  11.  
  12.     @Override 
  13.     public String parseOrigin(HttpServletRequest request) { 
  14.         String origin = request.getHeader("origin"); 
  15.         if(StringUtils.isEmpty(origin)) { 
  16.             log.warn("origin must not null"); 
  17.             throw new IllegalArgumentException("request origin must not null"); 
  18.         } 
  19.         return origin; 
  20.     } 

配置设置区分来源为:yijiaoqian

9.3 解决RestFul风格的请求

例如:/selectOrderInfoById/2 、 /selectOrderInfoById/1 需要转为/selectOrderInfoById/{number}

  1. /** 
  2. * @vlog: 高于生活,源于生活 
  3. * @desc: 类的描述:解决RestFule风格的请求 
  4.  *       eg:    /selectOrderInfoById/2     /selectOrderInfoById/1 需要转为/selectOrderInfoById/{number} 
  5. * @author: hejianhui 
  6. * @createDate: 2019/12/4 13:28 
  7. * @version: 1.0 
  8. */ 
  9. @Component 
  10. @Slf4j 
  11. public class NiuhUrlClean implements UrlCleaner { 
  12.     @Override 
  13.     public String clean(String originUrl) { 
  14.         log.info("originUrl:{}",originUrl); 
  15.  
  16.         if(StringUtils.isEmpty(originUrl)) { 
  17.             log.error("originUrl not be null"); 
  18.             throw new IllegalArgumentException("originUrl not be null"); 
  19.         } 
  20.         return replaceRestfulUrl(originUrl); 
  21.     } 
  22.  
  23.     /** 
  24.      * 方法实现说明:把/selectOrderInfoById/2 替换成/selectOrderInfoById/{number} 
  25.      * @author:hejianhui 
  26.      * @param sourceUrl 目标url 
  27.      * @return: 替换后的url 
  28.      * @exception: 
  29.      * @date:2019/12/4 13:46 
  30.      */ 
  31.     private String replaceRestfulUrl(String sourceUrl) { 
  32.         List<String> origins = Arrays.asList(sourceUrl.split("/")); 
  33.         StringBuffer targetUrl = new StringBuffer("/"); 
  34.  
  35.         for(String str:origins) { 
  36.             if(NumberUtils.isNumber(str)) { 
  37.                 targetUrl.append("/{number}"); 
  38.             }else { 
  39.                 targetUrl.append(str); 
  40.             } 
  41.  
  42.         } 
  43.         return targetUrl.toString(); 
  44.     } 

PS:以上代码提交在 Github :

https://github.com/Niuh-Study/niuh-cloud-alibaba.git


本文转载自网络,原文链接:https://www.toutiao.com/i6939342034457149956/

版权声明:本文转载自网络,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。本站转载出于传播更多优秀技术知识之目的,如有侵权请联系QQ/微信:153890879删除

相关文章
  • “礼物”域名12万元领衔!韩国最大比特

    “礼物”域名12万元领衔!韩国最大比特

  • 宋崝:浅谈ICANN的改革与国际化

    宋崝:浅谈ICANN的改革与国际化

  • 亚马逊和谷歌闹掰了:注册系列域名要对

    亚马逊和谷歌闹掰了:注册系列域名要对

  • “场外交易”域名OTC.cn易主大佬戴跃!

    “场外交易”域名OTC.cn易主大佬戴跃!

腾讯云代理商
海外云服务器