Sentinel学习(二)在Sring项目配置和使用Sentin

2019-11-12  本文已影响0人  nzdxwl

前面的文章创建了简单的Spring Boot应用,使用了Nacos作为配置和服务发现中心,现在再为它添加Sentinel流量监控功能。
以下我们为之前的项目添加 Sentinel功能,由于是Spring Boot以及Cloud,此次我们也是使用Spring Cloud Alibaba的组件spring-cloud-alibaba-sentinal,更多详细信息可以参考官方文档 Spring Cloud Alibaba Sentinel

配置:

  1. pom.xml中添加相关依赖项:

     <dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
         <version>0.9.0.RELEASE</version>
     </dependency>
    
     <dependency>
         <groupId>com.alibaba.csp</groupId>
         <artifactId>sentinel-core</artifactId>
         <version>1.6.3</version>
     </dependency>
    

由于spring-cloud-starter-alibaba-sentinel已经为我们引入了使用Sentinel所需大部分依赖项,我们只需要再添加sentinel-core依赖项即可。

  1. 应用中的配置
#指定dashbord地址
spring.cloud.sentinel.transport.dashboard=localhost:9090
#提前触发Sentinel初始化
spring.cloud.sentinel.eager=true
#指定sentinel数据源
spring.cloud.sentinel.datasource.ds2.nacos.server-addr=localhost:8848
spring.cloud.sentinel.datasource.ds2.nacos.data-id=sentinel
spring.cloud.sentinel.datasource.ds2.nacos.group-id=quickstart_cloud
spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
spring.cloud.sentinel.datasource.ds2.nacos.rule-type=flow

sentinel支持四种数据源,文件、nacos配置、zookeeper配置和apollo配置,由于我们已经应用nacos作为配置中心,因此也将sentinel的规则数据配置在nacos上面,具体dataid和group根据实际配置,以下使用json格式流量控制规则配置为例:

[
  {
    "resource": "/hello",
    "controlBehavior": 0,
    "count": 1,
    "grade": 1,
    "limitApp": "default",
    "strategy": 0
  },
  {
    "resource": "/test",
    "controlBehavior": 0,
    "count": 0,
    "grade": 1,
    "limitApp": "default",
    "strategy": 0
  },
  {
    "resource": "GET:http://www.taobao.com",
    "controlBehavior": 0,
    "count": 0,
    "grade": 1,
    "limitApp": "default",
    "strategy": 0
  }
]

配置解析:

代码

假设Service类有个方法想设置限流,那么可以使用 @SentinelResource(value = "这里填写资源名称")注解进行标识。更多的用法可以参考官方示例。

上一篇 下一篇

猜你喜欢

热点阅读