springcloud整合Sentinel实现接口限流

1.项目目录:

#yyds干货盘点# springcloud整合Sentinel实现接口限流_spring

2.代码实现:

添加依赖

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.cxh</groupId>
<artifactId>sentinel</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sentinel</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
<spring-cloud-alibaba-dependencies.version>2021.1</spring-cloud-alibaba-dependencies.version>
<spring-cloud-dependencies.version>2021.0.0</spring-cloud-dependencies.version>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud-dependencies.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-dependencies.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>0.9.0.RELEASE</version>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<optional>true</optional>
</dependency>
</dependencies>

yml配置

spring:
application:
name: sentinel

cloud:
sentinel:
transport:
dashboard: localhost:8080 #sentinel-dashboard的运行地址

server:
port: 8001

控制层

@RestController
public class SentinelController {

@Value("${server.port}")
private String port;

@GetMapping("/index")
public String index() {
return "index:" + port;
}
}

3.实现效果:

先下载sentinel-dashboard.jar,命令运行

java -jar sentinel-dashboard-1.6.0.jar

 浏览器打开:​
​http://localhost:8080/​​​,使用默认用户密码:sentinel进行登录


#yyds干货盘点# springcloud整合Sentinel实现接口限流_spring_02

#yyds干货盘点# springcloud整合Sentinel实现接口限流_spring_03

再运行项目sentinel,打开浏览器请求​​http://localhost:8001/index​​,刷新sentinel控制台就有sentinel项目的控制了。

#yyds干货盘点# springcloud整合Sentinel实现接口限流_spring_04

点击簇点链路,流控按钮添加限流规则

#yyds干货盘点# springcloud整合Sentinel实现接口限流_spring_05

新增后

#yyds干货盘点# springcloud整合Sentinel实现接口限流_spring_06

快速多次 请求​​http://localhost:8001/index​​ 出现:

Blocked by Sentinel (flow limiting)