操作场景
服务限流是最常见的一种服务自我保护措施之一,防止流量洪峰打垮服务。
Spring Cloud Tencent Rate Limit
模块内置了针对 Spring Web
和 Spring WebFlux
场景的限流Filter
,结合北极星的限流功能帮忙业务快速接入限流能力。前提条件
1. 在开始开发前,请确保您已经参见 下载 Maven下载安装了 Java 和 Maven。
2. 已创建 TSE 治理中心(北极星网格)实例,操作步骤详细参见 引擎管理。
操作步骤
步骤1:引入依赖
1.1 引入 spring cloud tencent 依赖
修改应用根目录下的 pom.xml,添加
dependencyManagement
:<dependencyManagement><dependencies><dependency><groupId>com.tencent.cloud</groupId><artifactId>spring-cloud-tencent-dependencies</artifactId><version>${version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>
注意:
1.2 引入 spring cloud tencent starter
方式一:只引入
spring-cloud-starter-tencent-polaris-ratelimit
。<dependency><groupId>com.tencent.cloud</groupId><artifactId>spring-cloud-starter-tencent-polaris-ratelimit</artifactId></dependency>
方式二:通过
spring-cloud-starter-tencent-all
引入 sct 所有 starters。<dependency><groupId>com.tencent.cloud</groupId><artifactId>spring-cloud-starter-tencent-all</artifactId><!-- 注意需要指定 type=pom--><type>pom</type></dependency>
如果使用 Spring Cloud 2020 及以后版本,还需要添加如下依赖:
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-bootstrap</artifactId></dependency>
步骤2:增加配置文件
1. 在项目的 main/resources 目录下创建 bootstrap.yml 文件。
2. 在 bootstrap.yml 文件中配置应用名、polaris(北极星)服务端地址等信息。服务端地址详细参见:引擎管理 > 客户端访问地址。
spring:application:name: ${application.name}cloud:polaris:address: grpc://${修改为第一步部署的 Polaris 服务地址}:8091namespace: default
步骤3:控制台配置限流规则
![](https://qcloudimg.tencent-cloud.cn/image/document/2dd386218ad78307ae3f4219a53bc468.png)
![](https://qcloudimg.tencent-cloud.cn/image/document/2dd386218ad78307ae3f4219a53bc468.png)
![](https://qcloudimg.tencent-cloud.cn/image/document/5d1af7f458af6404df48411c881fcf44.png)
![](https://qcloudimg.tencent-cloud.cn/image/document/5d1af7f458af6404df48411c881fcf44.png)
步骤4:启动应用
应用启动成功后,访问应用的 HTTP 接口,测试限流是否生效。如果请求被限流将会返回以下内容:
The request is deny by rate limit because the throttling threshold is reached