(1)环境搭建
导入Sentinel 的相应依赖
<dependency>
com.alibaba.csp
sentinel-spring-cloud-gateway-adapter
<version>a.b.c</version>
</dependency>
(2) 编写配置类
@Configuration
public class GatewayConfiguration {
private final List<ViewResolver> viewResolvers;
private final ServerCodecConfigurer serverCodecConfigurer;
public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) {
this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList); this.serverCodecConfigurer = serverCodecConfigurer;
}
/** * 配置限流的异常处理器:SentinelGatewayBlockExceptionHandler */
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() { return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer); }
/** * 配置限流过滤器 */
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GlobalFilter sentinelGatewayFilter() { return new SentinelGatewayFilter(); }
/** * 配置初始化的限流参数 */
@PostConstruct
public void initGatewayRules() {
Set<GatewayFlowRule> rules = new HashSet<>();
rules.add(
new GatewayFlowRule("order-service") //资源名称
.setCount(1) // 限流阈值
.setIntervalSec(1) // 统计时间窗口,单位是秒,默认是 1 秒 ); GatewayRuleManager.loadRules(rules);
}
}
(3) 编写配置类

(4)自定义异常提示 当触发限流后页面显示的是Blocked by Sentinel: FlowException。为了展示更加友好的限流提示, Sentinel支持自定义异常处理。
您可以在 GatewayCallbackManager 注册回调进行定制:
setBlockHandler :注册函数用于实现自定义的逻辑处理被限流的请求,对应接口为 BlockRequestHandler 。默认实现为 DefaultBlockRequestHandler ,当被限流时会返回类似 于下面的错误信息: Blocked by Sentinel: FlowException 。

(5) 参数限流
上面的配置是针对整个路由来限流的,如果我们只想对某个路由的参数做限流,那么可以使用参数限流 方式:

通过指定PARAM_PARSE_STRATEGY_URL_PARAM表示从url中获取参数,setFieldName指定参数名称
(6) 自定义API分组


网友评论