SpringBoot Sentinel Nacos ( 规则双向同步+自定义响应 )

下载Sentinel

为了满足需求,本文需要直接下载源码(后面需要修改源码)
下载地址:https://github.com/alibaba/Sentinel

image.png

首先可以先启动一下界面是啥效果 ( 端口自行配置,默认8080 )
image.png

访问页面
image.png

一、SpringBoot 项目Sentinel (简单版,了解)

以下更改位置:你自己的项目中

在pom.xml文件中依耐

  <!--父工程中引用-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.4.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <!--项目里面引用-->
    <dependency>
          <groupId>com.alibaba.cloud</groupId>
          <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>

配置文件中配置:

#Sentinel 对应的地址
spring.cloud.sentinel.transport.dashboard=127.0.0.1:8890
配置完成

启动项目,在控制台就能看见了,然后根据需要配置规则
缺点:配置的规则是存储到项目的内存中,下次重启失效,需要重新配置

二、SpringBoot 项目Sentinel (Nacos配置版,Nacos同步到 Sentinel )

以下更改位置:你自己的项目中
  <!--父工程中引用-->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.4.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <!--项目里面引用-->
    <dependency>
          <groupId>com.alibaba.cloud</groupId>
          <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
    </dependency>
    <!--简单版: 基础上,新增配置-->
       <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-datasource-nacos</artifactId>
       </dependency>
       <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-transport-simple-http</artifactId>
       </dependency>
       <!--spring-cloud-starter-alibaba-nacos-discovery 或者以下-->
       <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
       </dependency>

配置文件中配置:

#Sentinel 对应的地址
spring.cloud.sentinel.transport.dashboard=127.0.0.1:8890
#简单版: 基础上,新增配置
#${nacos.config.server-addr}代表nacos地址,例如:127.0.0.1:8848
#-flow-rules 和 SENTINEL_GROUP 配置系统默认(可自定义),双向同步的时候需要指定,不建议自定义,不然还得修改源码
spring.cloud.sentinel.datasource.flow.nacos.server-addr=${nacos.config.server-addr}
spring.cloud.sentinel.datasource.flow.nacos.dataId=${spring.application.name}-flow-rules
spring.cloud.sentinel.datasource.flow.nacos.groupId=SENTINEL_GROUP
spring.cloud.sentinel.datasource.flow.nacos.rule-type=flow
spring.cloud.sentinel.datasource.flow.nacos.data-type=json

大功告成
在nacos中配置你需要的规则,在sentinel web页面上就能看到了
例如:


image.png
[
    {
        "resource":"/home",
        "limitApp":"default",
        "grade":1,
        "count":1,
        "strategy":0,
        "controlBehavior":0,
        "clusterMode":false
    }
]

resource: 资源名称
limitApp: 来源应用
grade:阈值类型,0表示线程数,1表示QPS;
count:单机阈值;
strategy: 流控模式,0表示直接,1表示关联,2表示链路
controlBehavior:流控效果,0表示快速失败,1表示Warm Up,2表示排队等待;
clusterMode:是否集群

验证限流功能

启动Nacos服务
启动spring boot服务
启动sentinel-dashboard服务


image.png

image.png

image.png

三、SpringBoot 项目Sentinel (Sentinel 同步到 Nacos )

修改 sentinel-dashboard 源码

1.修改pom.xml中的sentinel-datasource-nacos的依赖,将<scope>test</scope>注释掉,这样才能在主程序中使用。

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

2.找到resources/app/scripts/directives/sidebar/sidebar.html中的这段代码

<li ui-sref-active="active">
    <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>

3.用来编写针对Nacos的扩展实现,复制一份


image.png

4.修改配置,对应的Nacos地址


image.png
    @Bean
    public ConfigService nacosConfigService() throws Exception {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1:8848");
        return ConfigFactory.createConfigService(properties);
    }
如果你的项目配置dataId 和 groupId 不是默认的,需要修改以下
image.png

image.png

image.png

5.修改com.alibaba.csp.sentinel.dashboard.controller.v2.FlowControllerV2中DynamicRuleProvider和DynamicRulePublisher注入的Bean,改为上面我们编写的针对Apollo的实现

@Autowired
@Qualifier("flowRuleNacosProvider")
private DynamicRuleProvider<List<FlowRuleEntity>> ruleProvider;
@Autowired
@Qualifier("flowRuleNacosPublisher")
private DynamicRulePublisher<List<FlowRuleEntity>> rulePublisher;
配置已完成,在Sentinel web页面修改规则,Nacos上面就能同步修改了。

四、自定义响应

系统默认返回的 Blocked by Sentinel (flow limiting) 在使用过程中显然不可取,需要自行修改。

在你的SpringBoot项目中配置如下:
// 新版已经修改为实现 BlockExceptionHandler ,老版实现 UrlBlockHandler 
@Configuration
public class SentinelException implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        ErrorResponse errorResponse = new ErrorResponse();
        if (e instanceof FlowException) {
            errorResponse.setMsg("被限流了");
            errorResponse.setStatus(1);
        } else if (e instanceof DegradeException) {
            errorResponse.setMsg("服务降级了");
            errorResponse.setStatus(2);
        } else if (e instanceof ParamFlowException) {
            errorResponse.setMsg("被限流了");
            errorResponse.setStatus(3);
        } else if (e instanceof SystemBlockException) {
            errorResponse.setMsg("被系统保护了");
            errorResponse.setStatus(4);
        } else if (e instanceof AuthorityException) {
            errorResponse.setMsg("被授权了");
            errorResponse.setStatus(5);
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(message));
    }
}

/**
 * 简单的响应结构体
 */
class ErrorResponse {
    private Integer status;
    private String msg;
    public Integer getStatus() {
        return status;
    }
    public static Object builder() {
        return null;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,820评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,648评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,324评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,714评论 1 297
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,724评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,328评论 1 310
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,897评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,804评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,345评论 1 318
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,431评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,561评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,238评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,928评论 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,417评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,528评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,983评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,573评论 2 359

推荐阅读更多精彩内容