Spring Boot集成 Sentinel 实现接口流量控制

爱写Bug的麦洛
• 阅读 1888

Spring Boot集成 Sentinel 实现接口流量控制

Hello,大家好,我是麦洛,今天带大家来了解一下SpringBoot如何继承Sentinel来实现接口流量控制

Sentinel控制台搭建

在我的上一篇文章阿里出品的Sentinel到底是个什么玩意?中,已经介绍过如何准备Sentinel控制台,大家可以直接参考;

Sentinel 客户端

项目搭建

首先我们来创建一个测试项目,这里初始化项目的url建议大家填写阿里云的地址,会有惊喜😅

http://start.aliyun.com

Spring Boot集成 Sentinel 实现接口流量控制

接下来就是常规操作,一路next,在下图的位置稍微注意一下

Spring Boot集成 Sentinel 实现接口流量控制

说明:

同大家以前创建项目一样,只需要在这里勾选Sentinel就可以啦🚀

项目创建好以后,我们发现pom文件中引入了下面的依赖

Spring Boot集成 Sentinel 实现接口流量控制

有的小伙伴看网上博客,也会有下面的方式,指定版本号

 <!-- sentinel -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>

如果你使用我推荐的阿里云的Url,会发现Sentinel的版本号都定义父工程,Cloud的各个组件的兼容性就不要大家操心了

 <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

打开项目配置文件,会发现它已经为我们自动加好了配置,真的超级方便👏

server.port=8083
# 应用名称
spring.application.name=springcloud-sentinel
# Sentinel 控制台地址
spring.cloud.sentinel.transport.dashboard=localhost:8080
# 取消Sentinel控制台懒加载
# 默认情况下 Sentinel 会在客户端首次调用的时候进行初始化,开始向控制台发送心跳包
# 配置 sentinel.eager=true 时,取消Sentinel控制台懒加载功能
spring.cloud.sentinel.eager=true
# 如果有多套网络,又无法正确获取本机IP,则需要使用下面的参数设置当前机器可被外部访问的IP地址,供admin控制台使用
# spring.cloud.sentinel.transport.client-ip=# sentinel 配置
spring.application.name=frms
spring.cloud.sentinel.transport.dashboard=localhost:8080
spring.cloud.sentinel.transport.heartbeat-interval-ms=500

如何定义资源

编程式定义

官网提供的demo

package com.milo.sentinel;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.ArrayList;
import java.util.List;

/**
 * 项目入口
 * @author Milo Lee
 * @date 2021-3-20 19:07
 *
 */
@SpringBootApplication
public class SentinelApplication {

    public static void main(String[] args) {
        SpringApplication.run(SentinelApplication.class, args);

        // 配置规则.
        initFlowRules();
        while (true) {
            // 1.5.0 版本开始可以直接利用 try-with-resources 特性
            try (Entry entry = SphU.entry("HelloWorld")) {
                // 被保护的逻辑
                Thread.sleep(300);
                System.out.println("hello world");
            } catch (BlockException | InterruptedException ex) {
                // 处理被流控的逻辑
                System.out.println("blocked!");
            }
        }

    }

    private static void initFlowRules(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("HelloWorld");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(20);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }

}

注解式定义

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(ServiceApplication.class, args);
    }
}

@Service
public class TestService {

    @SentinelResource(value = "sayHello")
    public String sayHello(String name) {
        return "Hello, " + name;
    }
}

@RestController
public class TestController {

    @Autowired
    private TestService service;

    @GetMapping(value = "/hello/{name}")
    public String apiHello(@PathVariable String name) {
        return service.sayHello(name);
    }
}

@SentinelResource 注解用来标识资源是否被限流、降级。上述例子上该注解的属性 sayHello 表示资源名。

启动控制台

java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.1.jar

Spring Boot集成 Sentinel 实现接口流量控制

控制台操作介绍

控制台的操作我们用编程式定义的例子来演示,大家启动我们的服务

Spring Boot集成 Sentinel 实现接口流量控制

我们会发现除了sentinel-dashboard之外,多了一个milolee-sentinel,这个就是我们的服务,它的名称其实对应我们配置文件定义的应用名称:

# 应用名称
spring.application.name=milolee-sentinel

点击机器列表,这这里如果能发现你的机器,那就是成功上线了

Spring Boot集成 Sentinel 实现接口流量控制

实时监控

Spring Boot集成 Sentinel 实现接口流量控制

簇点链路

Spring Boot集成 Sentinel 实现接口流量控制

流控规则配置

给我们的资源HelloWorld配置流控规则,它的QPS(每秒请求数)为1,如图:

Spring Boot集成 Sentinel 实现接口流量控制

通过查看实时监控,我们发现已经生效

Spring Boot集成 Sentinel 实现接口流量控制

降级规则配置

给我们的资源HelloWorld添加一个降级规则配置,如果QPS大于1,且平均响应时间大于20ms,则接口下来接口在2秒钟无法访问,之后自动恢复。

Spring Boot集成 Sentinel 实现接口流量控制

目前这些规则仅在内存态生效,应用重启之后,该规则会丢失。后续文章我们会继续学习动态规则

Spring Boot集成 Sentinel 实现接口流量控制

关于控制台的使用,大家可以参考官方文档,比较详细https://sentinelguard.io/zh-cn/docs/dashboard.html

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
京东云开发者 京东云开发者
6个月前
Java服务总在半夜挂,背后的真相竟然是... | 京东云技术团队
最近有用户反馈测试环境Java服务总在凌晨00:00左右挂掉,用户反馈Java服务没有定时任务,也没有流量突增的情况,Jvm配置也合理,莫名其妙就挂了
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这