【郑州研发中心】sentinel规则数据持久化nacos

简介: sentinel是阿里开源的流控规则引擎, 但是sentinel dashboard是将数据规则持久化到内存中, 当服务重新启动时,规则会消失,在生产环境中使用是不推荐的。因此本文主要是关于如何对sentinelDashboard页面配置的数据进行持久化,以及sentinelDashboard和nacos之间规则数据的双向同步.

一.sentinel介绍

随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式服务架构的流量控制组件,主要以流量为切入点,从限流、流量整形、熔断降级、系统负载保护、热点防护等多个维度来帮助开发者保障微服务的稳定性。
官网 git: https://github.com/alibaba/Sentinel/wiki
本文主要是讲解如何将sentinelDashboard页面配置的规则数据如何与nacos进行互相转化和同步。sentinelDashboard页面如图所示:
image.png
使用sentinel流控的方式有基于注解的方式,但是代码侵入较大,本文主要讲解的是使用sentinel控制台最小化的对应用进行流控改造。

二.下载dashborad与启动

在github上面下载sentinel(sentinel源码),然后找到sentinelDashboard模块进行启动即可,默认端口8080,本文修改了端口为8020,启动之后如图所示:
image.png

三.应用对接sentinel

在pom文件中加入依赖

  < dependency >
            < groupId>org.springframework.cloud< /groupId >
            < artifactId>spring-cloud-starter-openfeign< /artifactId >
            < version>2.1.1.RELEASE</version >
            < exclusions >
                < exclusion >
                    < groupId>com.netflix.archaius< /groupId >
                    < artifactId>archaius-core< /artifactId >
                </exclusion >
            </exclusions >
        </dependency >
        < !-- sentinel start -- >
        < !--  sentinel核心库 -- >
          < dependency >
              < groupId >com.alibaba.csp< /groupId >
              < artifactId >sentinel-core< /artifactId >
              < version >1.8.1< /version >
          < /dependency >
        < !-- 通过nacos持久化流控规则 -- >
        < dependency >
            < groupId >com.alibaba.csp< /groupId >
            < artifactId >sentinel-datasource-nacos< /artifactId >
            < version >1.8.1< /version >
        < /dependency >
        < !-- sentinel 整合spring cloud alibaba -- >
        < dependency >
            < groupId >com.alibaba.cloud< /groupId >
            < artifactId >spring-cloud-starter-alibaba-sentinel< /artifactId >
            < version >2.1.2.RELEASE< /version >
            < exclusions >
                < exclusion >
                    < artifactId >sentinel-core< /artifactId >
                    < groupId >com.alibaba.csp< /groupId >
                < /exclusion >
            < /exclusions >
        < /dependency >
        < !-- sentinel客户端与dashboard通信依赖 -- >
        < dependency >
            < groupId >com.alibaba.csp< /groupId >
            < artifactId >sentinel-transport-simple-http< /artifactId >
            < version >1.8.1< /version >
        < /dependency >

配置文件中新增配置:
image.png

spring:
  application:
    name: sentinel-demo
  cloud:
    sentinel:
      transport:
        dashboard: localhost:8020
        port: 8719
      ###心跳检测开启
      eager: true
      ###配置数据源
      datasource:
        ###流控规则
        flow:
          nacos:
            server-addr: localhost:8848
            ###与dashboard中的设置的dataId保持一致
            dataId: ${spring.application.name}-flow-rules
            ###与dashboard中的设置的groupId保持一致
            groupId: SENTINEL_GROUP
            data-type: json
            rule-type: flow
        ###熔断规则
        degrade:
          nacos:
            server-addr: localhost:8848
            dataId: ${spring.application.name}-degrade-rules
            groupId: SENTINEL_GROUP
            data-type: json
            rule-type: degrade

至此,客户端对接sentinle已完成,启动应用之后可以在dashboard页面查看到相应的服务.
image.png

四.sentinel规则数据持久化

  1. sentinelDashboard下载与启动
    1.1 从github下载sentinel-master到本地,打开sentinel-dashboard模块,如图所示:

image.png

1.2 将pom文件中的sentinel-datasource-nacos 的scope注释掉,如图所示:

image.png

1.3 代码改造
   sentinel的规则数据是由DynamicRuleProvider(读取)和DynamicRulePublisher(推送)两个接口定义的,我们只需要实现这两个接口即可;代码如下
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
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  xu.ming
 * @since 1.4.0
 */
@Component("flowRuleNacosProvider")
public class FlowRuleNacosProvider implements DynamicRuleProvider<List<FlowRuleEntity>> {

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

    @Override
    public List<FlowRuleEntity> getRules(String appName) throws Exception {
        String rules = configService.getConfig(
                appName + NacosConfigUtil.FLOW_DATA_ID_POSTFIX,
                NacosConfigUtil.GROUP_ID, 3000);
        if (StringUtil.isEmpty(rules)) {
            return new ArrayList<>();
        }
        return converter.convert(rules);
    }
}
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.NacosConfigUtil;
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  xu.ming
 * @since 1.4.0
 */
@Component("flowRuleNacosPublisher")
public class FlowRuleNacosPublisher implements DynamicRulePublisher<List<FlowRuleEntity>> {

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


    @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 + NacosConfigUtil.FLOW_DATA_ID_POSTFIX,
                NacosConfigUtil.GROUP_ID, converter.convert(rules));
    }
}

由于sentinelDashboard需要依赖nacos,我们还需要在配置文件中添加nacos相关的配置:
如图所示:
image.png

####xu.ming 新增nacos配置
nacos.address=localhost:8848
nacos.namespace=30e60261-cfc4-4176-a816-1db3b1e0cb17
nacos.username=nacos
nacos.password=nacos

image.png

@Configuration
public class NacosConfig {
     @Value("${nacos.address}")
     private String address;
     @Value("${nacos.namespace}")
     private String namespace;
     @Value("${nacos.username}")
     private String username;
     @Value("${nacos.password}")
     private String password;
    @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, address);
        properties.put(PropertyKeyConst.NAMESPACE, namespace);
        properties.put(PropertyKeyConst.USERNAME, username);
        properties.put(PropertyKeyConst.PASSWORD, password);
        return ConfigFactory.createConfigService(properties);
    }
}

将sentineDashboard--controller-->FlowControllerV2中的provider和publisher修改为刚才自定义的两个类.
image.png
修改页面代码:将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>  流控规则</a>
          </li>

修改为:

 <li ui-sref-active="active" ng-if="!entry.isGateway">
            <a ui-sref="dashboard.flow({app: entry.app})">
              <i class="glyphicon glyphicon-filter"></i>  流控规则</a>
          </li>

至此.流控规则dashboard页面修改完成,我们修改流控规则之后可以在nacos中看到其生成的规则数据.
image.png
image.png
image.png
同时,我们也可以在nacos中修改规则,dashboard页面也可以相应同步.
image.png
image.png

相关文章
sentinel-dashboard-1.8.0.jar开机自启动脚本
sentinel-dashboard-1.8.0.jar开机自启动脚本
359 0
|
SQL Java 数据库
Seata分布式事务源码分析
Seata分布式事务源码分析
234 0
|
关系型数据库 Java Nacos
Seata的部署和集成
部署Seata的tc-server
|
安全 物联网 测试技术
物联网平台的优势与价值
物联网平台的优势与价值
1218 49
物联网平台的优势与价值
|
2月前
|
人工智能 前端开发 机器人
10+热门 AI Agent 框架深度解析:谁更适合你的项目?
选型Agent框架不等于追热门!要选真正能跑得稳、适配团队能力与业务需求的框架。架构选错,轻则性能差,重则项目难推进。本文详解10大热门框架对比、5大新兴框架推荐及四步选型法,助你高效落地AI应用。
|
前端开发 Java 调度
SpringCloud微服务实战——搭建企业级开发框架(四十二):集成分布式任务调度平台XXL-JOB,实现定时任务功能
定时任务几乎是每个业务系统必不可少的功能,计算到期时间、过期时间等,定时触发某项任务操作。在使用单体应用时,基本使用Spring提供的注解即可实现定时任务,而在使用微服务集群时,这种方式就要考虑添加分布式锁来防止多个微服务同时运行定时任务而导致同一个任务重复执行。
1554 55
SpringCloud微服务实战——搭建企业级开发框架(四十二):集成分布式任务调度平台XXL-JOB,实现定时任务功能
|
网络安全 开发工具 数据安全/隐私保护
Git远程仓库Gitee的使用详解
Git远程仓库Gitee的使用详解
Git远程仓库Gitee的使用详解
|
关系型数据库 MySQL 数据库
SpringCloud2023中使用Seata解决分布式事务
对于分布式系统而言,需要保证分布式系统中的数据一致性,保证数据在子系统中始终保持一致,避免业务出现问题。分布式系统中对数据的操作要么一起成功,要么一起失败,必须是一个整体性的事务。Seata简化了这个使用过程。
297 2
|
网络协议 测试技术 Windows
Switchhosts工具的使用
Switchhosts工具的使用
614 0
|
消息中间件 Java Spring
SpringBoot实现RabbitMQ的定向交换机(SpringAMQP 实现Direct定向交换机)
SpringBoot实现RabbitMQ的定向交换机(SpringAMQP 实现Direct定向交换机)
170 1