如何使用 Sentinel 保护您的微服务(下)

大家好我是佩奇
发布于 2022-8-26 16:20
浏览
0收藏

作者 |  刘川川

来源 | 新钛云服(ID:newtyun)

转载请联系授权(微信ID:zlm935177782)

通过 Sentinel Dashboard 配置熔断

Sentinel Dashboard 可以设置三种不同的熔断模式:慢调用比例、异常比例、异常数,下面我们分别介绍:

  • 慢调用比例 (SLOW_REQUEST_RATIO):选择以慢调用比例作为阈值,需要设置允许的慢调用 RT(即最大的响应时间),请求的响应时间大于该值则统计为慢调用。当单位统计时长(statIntervalMs)内请求数目大于设置的最小请求数目,并且慢调用的比例大于阈值,则接下来的熔断时长内请求会自动被熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求响应时间小于设置的慢调用 RT 则结束熔断,若大于设置的慢调用 RT 则会再次被熔断。
    如何使用 Sentinel 保护您的微服务(下)-鸿蒙开发者社区
  • 异常比例:当单位统计时长(statIntervalMs)内请求数目大于设置的最小请求数目,并且异常的比例大于阈值,则接下来的熔断时长内请求会自动被熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求成功完成(没有错误)则结束熔断,否则会再次被熔断。异常比率的阈值范围是 [0.0, 1.0],代表 0% - 100%。
    如何使用 Sentinel 保护您的微服务(下)-鸿蒙开发者社区
  • 异常数 (ERROR_COUNT):当单位统计时长内的异常数目超过阈值之后会自动进行熔断。经过熔断时长后熔断器会进入探测恢复状态(HALF-OPEN 状态),若接下来的一个请求成功完成(没有错误)则结束熔断,否则会再次被熔断。
    如何使用 Sentinel 保护您的微服务(下)-鸿蒙开发者社区

以上就是三种熔断模式的介绍,熔断相对流控配置比较简单,只需要设置熔断检查开启条件与触发熔断条件即可。
接下来我们重启一下微服务,看看有什么效果?如下图所示:
如何使用 Sentinel 保护您的微服务(下)-鸿蒙开发者社区

前面我们创建的流控规则及熔断规则哪里去了?为什么已重启微服务就不见了?接下来我们就一起看看这个问题。
Sentinel 与 Nacos 整合实现规则持久化
上面的规则配置,都是存在内存中的。即如果应用重启,这个规则就会丢失。我们可以通过实现 DataSource 接口的方式,来自定义规则的存储数据源。通常我们的建议有:

  • 整合动态配置系统,如 ZooKeeper、Nacos、Apollo 等,动态地实时刷新配置规则
  • 结合 RDBMS、NoSQL、VCS 等来实现该规则
  • 配合 Sentinel Dashboard 使用

当微服务重启以后所有的配置规则都会丢失,其中的根源是默认微服务将 Sentinel 的规则保存在 JVM 内存中,当应用重启后 JVM 内存销毁,规则就会丢失。

接下来我们通过一个实例介绍 Sentinel 与 Nacos 的整合,把 Sentinel 的规则持久化到 Nacos 中。
项目准备
首先,我们快速构建演示工程 micro-service。
添加依赖
利用 Spring Initializr 向导创建 micro-service 工程,pom.xml 增加以下三项依赖。

<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>

配置 Nacos 与 Sentinel 客户端

server:
  port: 8080
spring:
  application:
    name: micro-service
  datasource:
    url: jdbc:mysql://localhost:3306/employee_directory?useSSL=false&serverTimezone=UTC
    username: employee
    password: employEE!@#123
  cloud:
    sentinel:
      transport:
        dashboard: 127.0.0.1:18080
      eager: true
    nacos:
      discovery:
        server-addr: localhost:8848
        username: nacos
        password: nacos
url:
  name: tyun
  address: www.tyun.cn
management:
  endpoints:
    web:
      exposure:
        include: '*'

演示代码

package cn.lavenliu.springboot.cruddemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.lavenliu.springboot.cruddemo.service.SentinelDemoService;

@RestController
@RequestMapping("/api")
public class SentinelDemoController {

    private SentinelDemoService sentinelDemoService;

    @GetMapping("/flowControl")
    public String testFlowRule() {
        return new String("创建成功");
    }
}

启动 micro-service,访问 http://localhost:8080/flowControl,如果出现如下所示,说明 micro-service 服务启动成功。

package cn.lavenliu.springboot.cruddemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.lavenliu.springboot.cruddemo.service.SentinelDemoService;

@RestController
@RequestMapping("/api")
public class SentinelDemoController {

    private SentinelDemoService sentinelDemoService;

    @GetMapping("/flowControl")
    public String testFlowRule() {
        return new String("创建成功");
    }
}

完整的代码放在了 Github 上面:https://github.com/TyunTech/spring-cloud-alibaba-sentinel-nacos-demo.git
流控规则持久化
工程创建完成,下面我们将 Sentinel 接入 Nacos 配置中心。
新增依赖
在 pom.xml 新增 sentinel-datasource-nacos 依赖。

<dependency>
    <groupId>com.alibaba.csp</groupId>
    <artifactId>sentinel-datasource-nacos</artifactId>
</dependency>

 

sentinel-datasource-nacos 是 Sentinel 为 Nacos 扩展的数据源模块,允许将规则数据存储在 Nacos 配置中心,在微服务启动时利用该模块 Sentinel 会自动在 Nacos下载对应的规则数据。
Nacos 中加载规则
在 Nacos 的 micro-service-dev.yml 配置中增加 Nacos下载规则,在原有的 Sentinel 配置下新增 datasource 选项。如下:

server:
  port: 8080
spring:
  application:
    name: micro-service
  datasource:
    url: jdbc:mysql://localhost:3306/employee_directory?useSSL=false&serverTimezone=UTC
    username: employee
    password: employEE!@#123
  cloud:
    sentinel:
      transport:
        dashboard: 127.0.0.1:18080
      eager: true
      datasource:
        flow:
          nacos:
            server-addr: ${spring.cloud.nacos.server-addr} 
            dataId: ${spring.application.name}-flow-rules
            groupId: DEFAULT_GROUP
            rule-type: flow
            username: nacos
            password: nacos
    nacos:
      server-addr: localhost:8848
      username: nacos
      password: nacos
url:
  name: tyun
  address: www.tyun.cn
management:
  endpoints:
    web:
      exposure:
        include: '*'

通过这一份配置,微服务在启动时就会自动从 Nacos 配置中心 DEFAULT_GROUP 分组下载 data-id 为 micro-service-flow-rules 的配置信息,并将其作为流控规则。
新增流控配置
在 Nacos 配置中心页面,新增 data-id 为 micro-service-flow-rules 的配置项。
如何使用 Sentinel 保护您的微服务(下)-鸿蒙开发者社区

这里 data-id 与 groups 与微服务应用的配置保持对应,最核心的配置内容采用 JSON 格式进行书写,我们来看下这段流控规则:

[
    {
        "resource": "/api/flowControl",
        "limitApp": "default",
        "grade": 1,
        "count": 2,
        "strategy": 0,
        "controlBehavior": 0,
        "clusterMode": false
    }
]

关于上述 Key 的含义如下:
如何使用 Sentinel 保护您的微服务(下)-鸿蒙开发者社区

其实上面的 JSON 配置,会生成如下 Dashboard 中的配置:
如何使用 Sentinel 保护您的微服务(下)-鸿蒙开发者社区

如何使用 Sentinel 保护您的微服务(下)-鸿蒙开发者社区

最后,我们启动应用来验证流控效果。使用 curl 访问 http://localhost:8080/api/flowControl:

[root@node01 alibaba]#  for i in {1..50}; do curl -w "\n" http://localhost:8080/api/flowControl; sleep 0.1; done
创建成功
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
[root@node01 alibaba]# 

我们每 0.1 秒就发起一次请求,可以看到 Sentinel 已经限流了,会出现 “Blocked by Sentinel (flow limiting)” 的错误信息,说明流控规则已生效。
接下来我们再来验证能否自动推送新规则,将 Nacos 配置中心中流控规则 count 选项改为 1。

[
    {
        "resource": "/api/flowControl",
        "limitApp": "default",
        "grade": 1,
        "count": 1,
        "strategy": 0,
        "controlBehavior": 0,
        "clusterMode": false
    }
]

这时可以看到应用也有相应的日志信息:

2022-04-28 12:53:40.379  INFO 18327 --- [-localhost_8848] c.a.n.client.config.impl.ClientWorker    : [fixed-localhost_8848] [polling-resp] config changed. dataId=micro-service-flow-rules, group=DEFAULT_GROUP
2022-04-28 12:53:40.379  INFO 18327 --- [-localhost_8848] c.a.n.client.config.impl.ClientWorker    : get changedGroupKeys:[micro-service-flow-rules+DEFAULT_GROUP]
2022-04-28 12:53:40.405  INFO 18327 --- [-localhost_8848] c.a.n.client.config.impl.ClientWorker    : [fixed-localhost_8848] [data-received] dataId=micro-service-flow-rules, group=DEFAULT_GROUP, tenant=null, md5=2e4c95b045fbc027c1d3b71199f263b9, content=[
    {
        "resource": "/api/flowControl",
        "limitApp": "default",
        "grade": 1,
 ..., type=json
2022-04-28 12:53:40.405  INFO 18327 --- [-localhost_8848] c.a.nacos.client.config.impl.CacheData   : [fixed-localhost_8848] [notify-listener] time cost=0ms in ClientWorker, dataId=micro-service-flow-rules, group=DEFAULT_GROUP, md5=2e4c95b045fbc027c1d3b71199f263b9, listener=com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource$1@4c21f712 
2022-04-28 12:53:40.406  INFO 18327 --- [update-thread-1] c.a.nacos.client.config.impl.CacheData   : [fixed-localhost_8848] [notify-ok] dataId=micro-service-flow-rules, group=DEFAULT_GROUP, md5=2e4c95b045fbc027c1d3b71199f263b9, listener=com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource$1@4c21f712

 

当新规则发布后,micro-service 控制台会立即收到下面的日志,说明新的流控规则即时生效。再次进行访问进行验证:

[root@node01 alibaba]#  for i in {1..50}; do curl -w "\n" http://localhost:8080/api/flowControl; sleep 0.1; done
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
创建成功
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)
Blocked by Sentinel (flow limiting)

至此,我们已经完成了 Sentinel 的规则并持久化到 Nacos 中。关于更多 Sentinel 的用法可以参考官方文档。

附录
目前已经有很多公司选择了 Spring Cloud Alibaba 开源组件进行开发,我们这里顺便介绍下 Spring Cloud Alibaba 的组成及其与 Spring Cloud 的对比。让大家对此有更多的选择。
Spring Cloud Alibaba 简介
我们先来简单了解下什么是 Spring Cloud Alibaba?Spring Cloud Alibaba 是由一些阿里巴巴的开源组件和云产品组成的。

Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。此项目包含开发分布式应用微服务的必需组件,方便开发者通过 Spring Cloud 编程模型轻松使用这些组件来开发分布式应用服务。

依托 Spring Cloud Alibaba,我们只需要添加一些注解和少量配置,就可以将 Spring Cloud 应用接入阿里微服务解决方案,通过阿里中间件来迅速搭建分布式应用系统。
技术选型推荐
在下面的表格中,我们总结了使用 Spring Cloud 来构建微服务架构时可以使用哪些组件,为大家做技术选型提供一个参考:

如何使用 Sentinel 保护您的微服务(下)-鸿蒙开发者社区

 

分类
标签
已于2022-8-26 16:20:39修改
收藏
回复
举报
回复
    相关推荐