Sentinel 之 整合Gateway
Sentinel 从 1.6.0 版本开始,提供了 Spring Cloud Gateway 的适配模块,可提供两种资源维度的限流:
1、route 维度:在 Spring 配置 路由条目时,资源名为 routeId
2、自定义 API 维度,用户可以用 Sentinel 提供的 API 来定义一些 API 分组
Gageway 模块加入 Sentinel 整合依赖:
<!-- Sentinel 配置 --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <!--sentinel 整合 gateway--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId> </dependency>
<!-- 接入控制台的依赖 非必须,按需选择使用 --> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-transport-simple-http</artifactId> </dependency> <!-- Sentinel 持久化配置,支持多种持久化数据源:file、nacos、zookeeper、apollo、redis、consul 非必须,按需选择,这里使用的是 Redis--> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-datasource-redis</artifactId> </dependency>
自定义编写一个配置类(通常不适用这种方式)
@Component public class GatewayConfiguration { @PostConstruct public void doInit() { //设置限流或降级的回调函数 new BlockRequestHandler() 匿名内部类 GatewayCallbackManager.setBlockHandler((ServerWebExchange serverWebExchange, Throwable throwable) -> ServerResponse.status(200).bodyValue("系统繁忙请稍后")); } }
在application.yml中配置sentinel控制台访问地址(通常使用这种方式)
更过详细配置请参看: https://gitee.com/chxlay/iserver-common/blob/master/iserver-common-sentinel/src/main/resources/application-sentinel.yml
# 官方文档: https://sentinelguard.io/zh-cn/docs/dashboard.html # 官方项目: https://github.com/alibaba/Sentinel/tree/master/sentinel-dashboard # Sentinel 相关配置 Feign 的支持 配置信息可以迁移到 Nacos 中 spring: cloud: sentinel: transport: # 配置 Sentinel dashboard 地址信息 dashboard: ${SENTINEL_HOST:iserver-sentinel}:${SENTINEL_PORT:8858} # Sentinel 默认端口号,加入被占用了,会自动从 8719 自动往后依次 +1 扫描,直到找到未占用的 port: 8719 scg: # 限流后的相应配置 fallback: content-type: application/json # 模式: response / redirect mode: response # 相应状态码 response-status: 200 # 相应消息体 response-body: '{"code":0,"message":"服务忙请稍后再试...","data":null}' # 请求重定向到某个地址 redirect: https://www.iserver-cloud.com
启动项目,在Sentinel控制台中添加关于资源的控制规则,sentinel在适配spring cloud gateway时提供了两种配置规则
route维度:即在spring配置文件配置的路由条数,资源名为对应的routeId
自定义API维度:用户可以利用Sentinel提供的API来自定义一些自定义分组
>>>>>>>> 接下一篇学习:https://www.cnblogs.com/Alay/p/15488126.html <<<<<<<<<<<
本文来自博客园,作者:Vermeer,转载请注明原文链接:https://www.cnblogs.com/chxlay/p/15488123.html