springgateway整合sentinel
时间: 2025-05-16 21:48:19 浏览: 24
### Spring Cloud Gateway 整合 Sentinel 的配置教程
#### 一、背景介绍
Spring Cloud Gateway 是基于 Reactor 和 Netty 构建的高性能 API 网关,而 Sentinel 则是一个用于流量防护和服务治理的开源框架。两者结合可以有效保护微服务架构中的资源免受高并发请求的影响。
以下是关于如何将 Spring Cloud Gateway 与 Sentinel 进行整合的具体方法[^4]:
---
#### 二、依赖引入
在项目的 `pom.xml` 文件中添加以下 Maven 依赖项:
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
```
上述依赖会自动集成 Sentinel 功能到 Spring Cloud Gateway 中[^2]。
---
#### 三、核心配置
编辑项目中的 `application.yml` 或 `application.properties` 文件,完成基础配置。以下是一个典型的 YAML 配置示例:
```yaml
server:
port: 8080
spring:
application:
name: gateway-service
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848 # Nacos 注册中心地址
gateway:
routes:
- id: example-route
uri: lb://example-service
predicates:
- Path=/api/example/**
filters:
- StripPrefix=1
sentinel:
transport:
dashboard: localhost:8081 # Sentinel 控制台地址
```
在此配置中,`sentinel.transport.dashboard` 参数指定了 Sentinel 控制台的服务地址。
---
#### 四、自定义过滤器逻辑
为了使 Sentinel 更好地适配 Spring Cloud Gateway,可以通过编写自定义过滤器来增强功能。例如,创建一个全局过滤器类并将其注册到应用上下文中:
```java
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 自定义逻辑:可以在进入网关前执行某些操作
String requestPath = exchange.getRequest().getPath().value();
// 将路径传递给 Sentinel 流量统计模块
Entry entry = null;
try {
entry = SphU.entry(requestPath);
return chain.filter(exchange);
} catch (BlockException e) {
// 当触发限流时返回特定响应
exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
return exchange.getResponse().setComplete();
} finally {
if (entry != null) {
entry.exit();
}
}
}
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}
```
以上代码片段展示了如何捕获请求路径并通过 Sentinel 的 `Entry` 接口对其进行监控和管理。
---
#### 五、启动类设置
修改应用程序的主入口类,确保其支持 Sentinel 的初始化工作。例如:
```java
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GatewayApplication {
private static final Logger log = LoggerFactory.getLogger(GatewayApplication.class);
public static void main(String[] args) {
// 设置属性以启用 Sentinel 对于网关的支持
System.setProperty("csp.sentinel.app.type", "1");
SpringApplication.run(GatewayApplication.class, args);
log.info(">>> GatewayApplication started successfully <<<");
}
/**
* 定义异常处理程序以便更好地反馈错误信息
*/
public BlockExceptionHandler blockHandler() {
return (request, exception, response) -> {
if (exception instanceof FlowException || exception instanceof ParamFlowException) {
response.setStatus(429); // Too Many Requests
} else if (exception instanceof DegradeException) {
response.setStatus(503); // Service Unavailable
} else if (exception instanceof AuthorityException) {
response.setStatus(403); // Forbidden
}
return response.getWriter().write("{\"error\":\"Blocked by Sentinel\"}");
};
}
}
```
这段代码设置了日志记录机制,并通过 `System.setProperty()` 方法启用了 Sentinel 的特殊模式。
---
#### 六、测试验证
部署完成后,访问目标接口(如 `/api/example/test`),观察是否能够正常调用下游服务;随后调整 Sentinel 控制台上对应的规则参数,确认限流降级策略生效情况。
---
阅读全文
相关推荐

















