4月25号,Sentinel 1.6.0 正式发布,带来 Spring Cloud Gateway 支持、控制台登陆功能、改进的热点限流和注解 fallback 等多项新特性,该出手时就出手,紧跟时代潮流,昨天刚发布,今天我就要给你们分享下如何使用!spring
Sentinel 1.6.0 引入了 Sentinel API Gateway Adapter Common 模块,此模块中包含网关限流的规则和自定义 API 的实体和管理逻辑:json
GatewayFlowRule:网关限流规则,针对 API Gateway 的场景定制的限流规则,能够针对不一样 route 或自定义的 API 分组进行限流,支持针对请求中的参数、Header、来源 IP 等进行定制化的限流。后端
ApiDefinition:用户自定义的 API 定义分组,能够看作是一些 URL 匹配的组合。好比咱们能够定义一个 API 叫 my_api,请求 path 模式为 /foo/ 和 /baz/ 的都归到 my_api 这个 API 分组下面。限流的时候能够针对这个自定义的 API 分组维度进行限流。api
其中网关限流规则 GatewayFlowRule 的字段解释以下:微信
用户能够经过 GatewayRuleManager.loadRules(rules) 手动加载网关规则,或经过 GatewayRuleManager.register2Property(property) 注册动态规则源动态推送(推荐方式)。app
首先你的有一个Spring Cloud Gateway的项目,若是没有,新建一个,增长Gateway和sentinel-spring-cloud-gateway-adapter的依赖,以下:ide
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId> <version>1.6.0</version> </dependency>
新建一个application.yml配置文件,用来配置路由:学习
server: port: 2001 spring: application: name: spring-cloud-gateway cloud: gateway: routes: - id: path_route uri: http://cxytiandi.com predicates: - Path=/course
配置了Path路由,等会使用 http://localhost:2001/course 进行访问便可。this
增长一个GatewayConfiguration 类,用于配置Gateway限流要用到的类,目前是手动配置的方式,后面确定是能够经过注解启用,配置文件中指定限流规则的方式来使用,固然这部分工做会交给Spring Cloud Alibaba来作,后面确定会发新版本的,你们耐心等待就好了。url
@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,限流后异常处理 * @return */ @Bean @Order(Ordered.HIGHEST_PRECEDENCE) public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() { return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer); } /** * 配置SentinelGatewayFilter * @return */ @Bean @Order(-1) public GlobalFilter sentinelGatewayFilter() { return new SentinelGatewayFilter(); } @PostConstruct public void doInit() { initGatewayRules(); } /** * 配置限流规则 */ private void initGatewayRules() { Set<GatewayFlowRule> rules = new HashSet<>(); rules.add(new GatewayFlowRule("path_route") .setCount(1) // 限流阈值 .setIntervalSec(1) // 统计时间窗口,单位是秒,默认是 1 秒 ); GatewayRuleManager.loadRules(rules); } }
咱们定义的资源名称是path_route,也就是application.yml中的路由ID,一致就行。
在一秒钟内屡次访问http://localhost:2001/course就能够看到限流启做用了。
上面的配置是针对整个路由来限流的,若是咱们只想对某个路由的参数作限流,那么可使用参数限流方式:
rules.add(new GatewayFlowRule("path_route") .setCount(1) .setIntervalSec(1) .setParamItem(new GatewayParamFlowItem() .setParseStrategy(SentinelGatewayConstants.PARAM_PARSE_STRATEGY_URL_PARAM).setFieldName("vipType") ) );
经过指定PARAM_PARSE_STRATEGY_URL_PARAM表示从url中获取参数,setFieldName指定参数名称
假设我有下面两个路由,我想让这两个路由共用一个限流规则,那么咱们能够自定义进行组合:
- id: path2_route uri: http://cxytiandi.com predicates: - Path=/article - id: path3_route uri: http://cxytiandi.com predicates: - Path=/blog/**
自定义分组代码:
private void initCustomizedApis() { Set<ApiDefinition> definitions = new HashSet<>(); ApiDefinition api1 = new ApiDefinition("customized_api") .setPredicateItems(new HashSet<ApiPredicateItem>() {{ // article彻底匹配 add(new ApiPathPredicateItem().setPattern("/article")); // blog/开头的 add(new ApiPathPredicateItem().setPattern("/blog/**") .setMatchStrategy(SentinelGatewayConstants.PARAM_MATCH_STRATEGY_PREFIX)); }}); definitions.add(api1); GatewayApiDefinitionManager.loadApiDefinitions(definitions); }
而后咱们须要给customized_api这个资源进行配置:
rules.add(new GatewayFlowRule("customized_api") .setCount(1) .setIntervalSec(1) );
前面咱们有看到,当触发限流后页面显示的是Blocked by Sentinel: FlowException,正常状况下,就算给出提示也要跟后端服务的数据格式同样,若是你后端都是JSON格式的数据,那么异常的提示也要是JSON的格式,因此问题来了,咱们怎么去自定义异常的输出?
前面咱们有配置SentinelGatewayBlockExceptionHandler,个人注释写的限流后异常处理,咱们能够进去看下源码就知道是否是异常处理了。下面贴出核心的代码:
private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) { return response.writeTo(exchange, contextSupplier.get()); } @Override public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) { if (exchange.getResponse().isCommitted()) { return Mono.error(ex); } // This exception handler only handles rejection by Sentinel. if (!BlockException.isBlockException(ex)) { return Mono.error(ex); } return handleBlockedRequest(exchange, ex) .flatMap(response -> writeResponse(response, exchange)); }
重点在于writeResponse这个方法,咱们只要把这个方法改掉,返回本身想要返回的数据就好了,能够自定义一个SentinelGatewayBlockExceptionHandler的类来实现。
好比:
public class JsonSentinelGatewayBlockExceptionHandler implements WebExceptionHandler { // ........ }
而后复制SentinelGatewayBlockExceptionHandler中的代码到JsonSentinelGatewayBlockExceptionHandler 中,只改动writeResponse一个方法便可。
private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) { ServerHttpResponse serverHttpResponse = exchange.getResponse(); serverHttpResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8"); byte[] datas = "{\"code\":403,\"msg\":\"限流了\"}".getBytes(StandardCharsets.UTF_8); DataBuffer buffer = serverHttpResponse.bufferFactory().wrap(datas); return serverHttpResponse.writeWith(Mono.just(buffer)); }
最后将配置的SentinelGatewayBlockExceptionHandler改为JsonSentinelGatewayBlockExceptionHandler 。
@Bean @Order(Ordered.HIGHEST_PRECEDENCE) public JsonSentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() { return new JsonSentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer); }