【郑州研发中心】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

相关文章
|
负载均衡 算法 Java
蚂蚁面试:Nacos、Sentinel了解吗?Springcloud 核心底层原理,你知道多少?
40岁老架构师尼恩分享了关于SpringCloud核心组件的底层原理,特别是针对蚂蚁集团面试中常见的面试题进行了详细解析。内容涵盖了Nacos注册中心的AP/CP模式、Distro和Raft分布式协议、Sentinel的高可用组件、负载均衡组件的实现原理等。尼恩强调了系统化学习的重要性,推荐了《尼恩Java面试宝典PDF》等资料,帮助读者更好地准备面试,提高技术实力,最终实现“offer自由”。更多技术资料和指导,可关注公众号【技术自由圈】获取。
蚂蚁面试:Nacos、Sentinel了解吗?Springcloud 核心底层原理,你知道多少?
|
Java 测试技术 Nacos
|
监控 算法 Java
高并发架构设计三大利器:缓存、限流和降级问题之配置Sentinel的流量控制规则问题如何解决
高并发架构设计三大利器:缓存、限流和降级问题之配置Sentinel的流量控制规则问题如何解决
280 0
|
Java Nacos Maven
Sentinel1.8.6更改配置同步到nacos(项目是Gateway)
Sentinel1.8.6 nacos springcloud springcloud-alibaba gateway
572 0
|
监控 数据挖掘 索引
深度剖析Sentinel热点规则
深度剖析Sentinel热点规则
377 1
|
Java Nacos Sentinel
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(九)Nacos+Sentinel+Seata
【Springcloud Alibaba微服务分布式架构 | Spring Cloud】之学习笔记(九)Nacos+Sentinel+Seata
2212 0
|
7月前
|
存储 Kubernetes 安全
Nacos-Controller 2.0:使用 Nacos 高效管理你的 K8s 配置
无论是使用 Nacos-Controller 实现配置的双向同步,还是直接在应用中接入 Nacos SDK 以获得更高级的配置管理特性,都能显著提升配置管理的灵活性、安全性和可维护性。使用 Nacos,您能够更好地管理和优化您的应用配置,从而提高系统的稳定性和可靠性。
621 49
|
11月前
|
存储 网络协议 Nacos
高效搭建Nacos:实现微服务的服务注册与配置中心
Nacos(Dynamic Naming and Configuration Service)是阿里巴巴开源的一款动态服务发现、配置管理和服务管理平台。它旨在帮助开发者更轻松地构建、部署和管理分布式系统,特别是在微服务架构中。
1829 82
高效搭建Nacos:实现微服务的服务注册与配置中心
|
11月前
|
JSON Java Nacos
SpringCloud 应用 Nacos 配置中心注解
在 Spring Cloud 应用中可以非常低成本地集成 Nacos 实现配置动态刷新,在应用程序代码中通过 Spring 官方的注解 @Value 和 @ConfigurationProperties,引用 Spring enviroment 上下文中的属性值,这种用法的最大优点是无代码层面侵入性,但也存在诸多限制,为了解决问题,提升应用接入 Nacos 配置中心的易用性,Spring Cloud Alibaba 发布一套全新的 Nacos 配置中心的注解。
1061 149
|
7月前
|
存储 人工智能 测试技术
Nacos托管LangChain应用Prompts和配置,助力你的AI助手快速进化
AI 应用开发中,总有一些让人头疼的问题:敏感信息(比如 API-KEY)怎么安全存储?模型参数需要频繁调整怎么办?Prompt 模板改来改去,每次都得重启服务,太麻烦了!别急,今天我们就来聊聊如何用 Nacos 解决这些问题。

热门文章

最新文章