Sentinel 整合 Spring Cloud Gateway 实现网关层面的流量控制,主要步骤如下:
- 添加依赖:
在 Gateway 项目的pom.xml
文件中添加 Sentinel 的 Gateway 适配器依赖。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel-gateway</artifactId>
</dependency>
- 配置启动类:
在 Gateway 应用的启动类上添加@EnableSentinelGateway
注解启用 Sentinel 网关流控。
import com.alibaba.cloud.sentinel.gateway.SentinelGatewayAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapper;
@SpringBootApplication
@EnableDiscoveryClient
@EnableSentinelGateway // 启用 Sentinel 网关流控
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
// 可以定义自定义路由映射规则等其他配置
}
-
配置 Sentinel 控制台:
需要在 Sentinel 控制台上配置网关流控规则。在 Sentinel 控制台 -> 流控规则 -> 新增网关流控规则页面,你可以根据 API 路径、请求方法、参数等多个维度设置限流规则。 -
YAML 配置文件(可选):
如果需要通过配置文件来配置 Sentinel 相关属性,可以在 application.yml 或 application.properties 中进行配置,例如:
spring:
cloud:
gateway:
routes:
- id: sentinel_route
uri: lb://service-provider
predicates:
- Path=/provider/**
filters:
- name: SentinelGatewayFilter # 添加 Sentinel 网关过滤器
args:
资源名称: /provider/**
阈值类型: QPS
阈值: 10
关联响应码: 429
sentinel:
transport:
dashboard: localhost:8080 # Sentinel 控制台地址
port: 8719 # 客户端与 Sentinel 控制台通信端口
这样,Sentinel 就可以对 Spring Cloud Gateway 中的请求进行流量控制了。在 Sentinel 控制台上配置的规则会实时生效,实现动态的流量控制管理。