springcloud Alibaba入门之sentinel使用Nacos进行持久化

上节我们在springcloud Alibaba 入门之采用Sentinel实现接口限流文章中简单知道了sentinel其中的一个作用,我们这里只用它来做限流的操作,但是有个问题不知道大家知道不,当我们将sentinel控制台重启之后,我们自己定义的限流规则会丢失,那么本篇
博客就是为了解决该问题而写的,全程采用的都是本地服务,大致分为了两步走:

  • 一是修改sentinel Dashboard的规则然后进行同步到nacos中
  • 二是在nacos管理台对我们限流的规则进行自定义的过程

首先我们来看修改sentinel Dashboard的规则,我们需要fork sentinel的源码在其基础上修改,fork 源码的地址为:Sentinel源码地址,具体的步骤如下:

  • a.首先我们来修改pom.xml中的sentinel-datasource-nacos的依赖,将<scope>test</scope>注释掉,这样做的目的是为了在我们的主程序中起到作用,代码如下:
 <!-- for Nacos rule publisher sample -->
    <dependency>
        <groupId>com.alibaba.csp</groupId>
        <artifactId>sentinel-datasource-nacos</artifactId>
        <scope>test</scope>
    </dependency>
  • b.接着我们需要修改resources/app/scripts/directives/sidebar/sidebar.html页面中的一段代码如:
 <li ui-sref-active="active" ng-if="!entry.isGateway">
        <a ui-sref="dashboard.flowV1({app: entry.app})">
          <i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;流控规则</a>
      </li>

修改之后为:

<li ui-sref-active="active">
        <a ui-sref="dashboard.flow({app: entry.app})">
          <i class="glyphicon glyphicon-filter"></i>&nbsp;&nbsp;流控规则
        </a>
 </li>
  • c.在com.alibaba.csp.sentinel.dashboard.rule包下新建一个nacos包,该包下主要存放我们对nacos的拓展规则以及配置的书写.
  • d.在nacos包下创建Nacos的配置类,代码如下:
''''
package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
import java.util.Properties;

/**
 * @author cb
 */
@Configuration
public class NacosConfig {

@Bean
public Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {
    return JSON::toJSONString;
}

@Bean
public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {
    return s -> JSON.parseArray(s, FlowRuleEntity.class);
}

@Bean
public ConfigService nacosConfigService() throws Exception {
    Properties properties = new Properties();
    properties.put(PropertyKeyConst.SERVER_ADDR, "localhost");
    return ConfigFactory.createConfigService(properties);
    }
}
  • e.我们需要对nacos的配置进行远程拉取,代码如下:
package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
 * @author cb
 */
@Component("flowRuleNacosProvider")
public class FlowRuleNacosProvider implements DynamicRuleProvider<List<FlowRuleEntity>> {

@Autowired
private ConfigService configService;
@Autowired
private Converter<String, List<FlowRuleEntity>> converter;

public static final String FLOW_DATA_ID_POSTFIX = "-sentinel";
public static final String GROUP_ID = "DEFAULT_GROUP";

@Override
public List<FlowRuleEntity> getRules(String appName) throws Exception {
    String rules = configService.getConfig(appName + FLOW_DATA_ID_POSTFIX, GROUP_ID, 3000);
    if (StringUtil.isEmpty(rules)) {
        return new ArrayList<>();
    }
    return converter.convert(rules);
}

简单的来说下该类中的方法getRules的作用,我们看到参数为appName,其中appName为我们sentinel控制台中的应用名称,这个我们在上节大概都知道,还有我们看到配置了public static final String FLOW_DATA_ID_POSTFIX = "-sentinel"这个参数,该参数主要的目的是我们在nacos中的dataId的后缀,代码如下:

spring.cloud.sentinel.datasource.ds.nacos.dataId=${spring.application.name}-sentinel
spring.cloud.sentinel.datasource.ds.nacos.groupId=DEFAULT_GROUP

那么方法中的configService#getConfig(...)该方法就是为了动态获取我们在nacos管理台上的配置属性.

  • f.完成了拉取远程的配置操作,我们需要将拉取的配置进行推送到sentinel平台完成展示,具体代码如下:
''''
package com.alibaba.csp.sentinel.dashboard.rule.nacos;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.util.AssertUtil;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 * @author cb
 */
@Component("flowRuleNacosPublisher")
public class FlowRuleNacosPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {

    @Autowired
    private ConfigService configService;
    @Autowired
    private Converter<List<FlowRuleEntity>, String> converter;

    public static final String FLOW_DATA_ID_POSTFIX = "-sentinel";
    public static final String GROUP_ID = "DEFAULT_GROUP";

    @Override
    public void publish(String app, List<FlowRuleEntity> rules) throws Exception {
        AssertUtil.notEmpty(app, "app name cannot be empty");
        if (rules == null) {
            return;
        }
        configService.publishConfig(app + FLOW_DATA_ID_POSTFIX, GROUP_ID, converter.convert(rules));
      }
}
  • g.这也是最后一步,我们需要修该com.alibaba.csp.sentinel.dashboard.controller.v2.FlowControllerV2中DynamicRuleProvider和DynamicRulePublisher注入的bean操作,代码如下:
@Autowired
@Qualifier("flowRuleNacosProvider")
private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
@Autowired
@Qualifier("flowRuleNacosPublisher")
private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;

到这里我们的sentinel Dashboard的修改完成了,启动它,我们会在控制台看到这样的日志输出:

微信截图_20191217214045.png

接着访问127.0.0.1:8080,会看到如图的界面:

微信截图_20191217214255.png

同样我们输入用户名和密码均为:sentinel,会看到如下图的主界面:

微信截图_20191217214322.png

那么以上便是关于sentinel Dashboard的修改操作,接下来是我们的重点,如何在nacos中定义我们的限流的规则

限流规则的定义

首先我们需要创建一个服务,我这里名字为alibaba-nacos-sentinel,没啥别的作用,主要是为了跟之前服务的对称,至于创建过程之前已经说了,接着我们来看需要的依赖,代码如下:

</parent>
<groupId>com.alibaba.sentinel</groupId>
<artifactId>alibaba-nacos-sentinel</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>alibaba-nacos-sentinel</name>
<description>利用sentinel实现限流</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- <dependency>
         <groupId>com.alibaba.cloud</groupId>
         <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
         <version>2.1.0.RELEASE</version>
     </dependency>-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>

    <!--nacos整合sentinel-->
    <dependency>
        <groupId>com.alibaba.csp</groupId>
        <artifactId>sentinel-datasource-nacos</artifactId>
        <version>1.7.0</version>
    </dependency>

</dependencies>
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Greenwich.SR3</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>0.9.0.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
  • 接下来我们来看看配置文件,代码如下:
server.port=9007
spring.application.name=alibaba-nacos
spring.cloud.sentinel.transport.dashboard=127.0.0.1:8080
spring.cloud.sentinel.datasource.ds.nacos.server-addr=127.0.0.1:8848
spring.cloud.sentinel.datasource.ds.nacos.dataId=${spring.application.name}-sentinel
spring.cloud.sentinel.datasource.ds.nacos.groupId=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds.nacos.rule-type=flow

目前是学习阶段所以只是简单的配置我所用到的,这样看着简洁,当然大家可以配置成.yml文件格式,看个人

  • 主程序,代码入下:
package com.alibaba.sentinel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * @author cb
 */
@SpringBootApplication
public class AlibabaNacosSentinelApplication {
public static void main(String[] args) {
    SpringApplication.run(AlibabaNacosSentinelApplication.class, args);
  }
}
  • 测试接口代码入下;
package com.alibaba.sentinel.controller
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@GetMapping("/hello")
public String hello(){
    return "hello Sentinel";
    }
}

一个简单的接口测试,到这里我们需要的服务代码的编写完成了,接着启动我的本地注册中心nacos,接着启动我的服务,然后在nacos的管理台上配置我们的限流规则,如图所示:

微信截图_20191217220333.png
  • 配置限流格式的代码如下:
   {
    "resource": "/hello",
    "limitApp": "default",
    "grade": 1,
    "count": 5,
    "strategy": 0,
    "controlBehavior": 0,
    "clusterMode": false
}

标准的json格式,同样我们就会在后台服务的日志中看到如图的信息:

微信截图_20191217220703.png

看到如图的信息,说明我们的配置能被服务加载到了,接着用postman来进行接口调用的测试,于此同时在我们sentinel 管理台上会出现相应服务的请求信息显示,如图:

微信截图_20191217221132.png

接着我们来查看流控规则,你会发现:

微信截图_20191217221326.png

那看到如图的信息,就说明我们借助于nacos管理台实现了限流规则的拉取和读取的过程,当然最重要的是持久化的过程,不信你可以关闭页面重新打开,配置的规则依然是存在的,到这里我们的目的也就达成了,关于sentinel的深入学习,大家可以看看官方文档....

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容