• sentinel和spring cloud gateway整合


    sentinel和spring cloud gateway整合

    注意: 控制台的改造这里我就不一一细说了。如果想了解的话可以到以下网址

    https://www.cnblogs.com/dabenxiang/p/14376990.html

    改造后的控制台gitee地址是:

    https://gitee.com/gzgyc/sentinel-dashboard.git

    背景介绍:

    Sentinel 1.6.0 引入了 Sentinel API Gateway Adapter Common 模块,此模块中包含网关限流的规则和自定义 API 的实体和管理逻辑:

    • GatewayFlowRule:网关限流规则,针对 API Gateway 的场景定制的限流规则,可以针对不同 route 或自定义的 API 分组进行限流,支持针对请求中的参数、Header、来源 IP 等进行定制化的限流。
    • ApiDefinition:用户自定义的 API 定义分组,可以看做是一些 URL 匹配的组合。比如我们可以定义一个 API 叫 my_api,请求 path 模式为 /foo/**/baz/** 的都归到 my_api 这个 API 分组下面。限流的时候可以针对这个自定义的 API 分组维度进行限流。

    spring cloud gateway代码配置

    从 1.6.0 版本开始,Sentinel 提供了 Spring Cloud Gateway 的适配模块,可以提供两种资源维度的限流:

    • route 维度:即在 Spring 配置文件中配置的路由条目,资源名为对应的 routeId
    • 自定义 API 维度:用户可以利用 Sentinel 提供的 API 来自定义一些 API 分组

    pom.xml的依赖配置:

     	 <dependency>
                <groupId>com.alibaba.csp</groupId>
                <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
                <version>${spring-boot.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-gateway</artifactId>
                <version>2.1.1.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-webflux</artifactId>
                <version>${spring-boot.version}</version>
            </dependency>
    
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-validation</artifactId>
                <version>${spring-boot.version}</version>
            </dependency>
    
            <dependency>
                <groupId>com.alibaba.csp</groupId>
                <artifactId>sentinel-datasource-nacos</artifactId>
            </dependency>
    
    

    application.yml的配置

    server:
      port: 8311
    spring:
      application:
        name: sentinel-nacos-gateway
      cloud:
        gateway:
          enabled: true
          discovery:
            locator:
              lower-case-service-id: true
          routes:
            # Add your routes here.
            - id: web
              uri: http://127.0.0.1:8701
              predicates:
                - Path=/web/**
            - id: user
              uri: http://127.0.0.1:8701
              predicates:
                - Path=/user/**
        sentinel:
          transport:
            port: 8719
            dashboard: localhost:18080
    

    上面的配置其实就是一些网关的配置:

    ​ /web/** 跳转到 http://127.0.0.1:8701/web/** ,

    ​ /user/** 跳转到http://127.0.0.1:8701/user/**

    我们这边把sentinel的相关规则直接持久化到nacos中,而sentinel的dashboard控制台也跟nacos整合一起:

    sentinel的配置文件:

    @Configuration
    public class GatewayConfiguration {
    
        private final List<ViewResolver> viewResolvers;
        private final ServerCodecConfigurer serverCodecConfigurer;
    
    
        String serverAddr = "localhost:8848";
    
        String  groupId = "SENTINEL_GROUP";
    
        String dataId = "sentinel-nacos-gateway-gateway-flow-rules";
    
        String apiGatewayDataId = "sentinel-nacos-gateway-gateway-api";
    
        String degradeDataId = "sentinel-nacos-gateway-degrade-rules";
    
    
    
        static {
            System.setProperty("csp.sentinel.app.type","1");
        }
    
    
        public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                    ServerCodecConfigurer serverCodecConfigurer) {
            this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
            this.serverCodecConfigurer = serverCodecConfigurer;
        }
    
        @Bean
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
            // Register the block exception handler for Spring Cloud Gateway.
            return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
        }
    
        @Bean
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public GlobalFilter sentinelGatewayFilter() {
            return new SentinelGatewayFilter();
        }
    
    
        @PostConstruct
        public void doInit() {
            initCustomizedApis();
            initGatewayRules();
        }
    
    
        //从nacos上动态读取api分组
        private void initCustomizedApis() {
    
            ReadableDataSource dataSource = new NacosDataSource(serverAddr, groupId, apiGatewayDataId, new Converter<String, Set<ApiDefinition>>() {
                @Override
                public Set<ApiDefinition> convert(String s) {
                    List<ApiPathDefinition> lists = JSONObject.parseArray(s, ApiPathDefinition.class);
    
                    Set<ApiDefinition> resultSet = new HashSet<>();
                    for (ApiPathDefinition apiPathDefinition : lists) {
                        resultSet.add(apiPathDefinition.toApiDefinition());
                    }
                    return  resultSet;
                }
            });
    
    
            GatewayApiDefinitionManager.register2Property(dataSource.getProperty());
        }
    
    
    
    
        private void initGatewayRules() {
    
            //从nacos上动态读取网关的流控规则
            ReadableDataSource dataSource = new NacosDataSource(serverAddr, groupId, dataId, new Converter<String, Set<GatewayFlowRule>>() {
    
                //把nacos读到的信息,转成List<FlowRule>
                @Override
                public Set<GatewayFlowRule> convert(String s) {
                    return  JSONObject.parseObject(s, new TypeReference<Set<GatewayFlowRule>>() {
                    });
    
                }
            });
    
            GatewayRuleManager.register2Property(dataSource.getProperty());
    
    
    
    
            //从nacos上动态读取降级规则
            ReadableDataSource degradeDataSource = new NacosDataSource(serverAddr, groupId, degradeDataId, new Converter<String, List<DegradeRule>>() {
    
                //把nacos读到的信息,转成List<FlowRule>
                @Override
                public List<DegradeRule> convert(String s) {
                    List<DegradeRule> degradeRules = JSONObject.parseObject(s, new TypeReference<List<DegradeRule>>() {
                    });
                    return degradeRules;
    
                }
            });
    
            DegradeRuleManager.register2Property(degradeDataSource.getProperty());
    
        }
    
    }
    
    

    API Gateway 端配置的重点:

    API Gateway 端使用时只需注入对应的 SentinelGatewayFilter 实例以及 SentinelGatewayBlockExceptionHandler 实例即可。

    与控制台整合的重点:

    在 API Gateway 端,用户只需要在原有启动参数的基础上添加如下启动参数即可标记应用为 API Gateway 类型:

    # 注:通过 Spring Cloud Alibaba Sentinel 自动接入的 API Gateway 整合则无需此参数
    -Dcsp.sentinel.app.type=1
    

    虽然我上面没有加-Dcsp.sentinel.app.type=1,但是也可以通过System.setProperty方法添加环境变量

    static {
        System.setProperty("csp.sentinel.app.type","1");
    }
    

    动态读取nacos上的配置:

    • initCustomizedApis方法: 从nacos上动态读取api分组的配置

    • initGatewayRules方法: 1.从nacos上动态读取网关的流控规则 2.nacos上动态读取降级规则

    sentinel网关的api讲解:

    ApiDefinition的讲解

            Set<ApiDefinition> definitions = new HashSet<>();
            ApiDefinition api1 = new ApiDefinition("web")
                    .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                        add(new ApiPathPredicateItem().setPattern("/web/**")
                                .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
                    }});
            definitions.add(api1);
            GatewayApiDefinitionManager.loadApiDefinitions(definitions);
    

    上面的这个是官方的api的例子,相当于的控制台的页面如下的配置:

    image-20210218162820651

    setMatchStrategy的参数:

    • SentinelGatewayConstants.URL_MATCH_STRATEGY_EXACT: 精确
    • SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX: 前缀
    • SentinelGatewayConstants.URL_MATCH_STRATEGY_REGEX: 正则

    GatewayFlowRule的api讲解

    网关限流规则 GatewayFlowRule 的字段解释如下:

    • resource:资源名称,可以是网关中的 route 名称或者用户自定义的 API 分组名称。

    • resourceMode:规则是针对 API Gateway 的 route(RESOURCE_MODE_ROUTE_ID)还是用户在 Sentinel 中定义的 API 分组(RESOURCE_MODE_CUSTOM_API_NAME),默认是 route。 注意这里: routeId:指的是:spring cloud gateway里面定义的routesId的,   API 分组: 则是ApiDefinition定义的资源

    • grade:限流指标维度,同限流规则的 grade 字段。

    • count:限流阈值

    • intervalSec:统计时间窗口,单位是秒,默认是 1 秒。

    • controlBehavior:流量整形的控制效果,同限流规则的 controlBehavior 字段,目前支持快速失败和匀速排队两种模式,默认是快速失败。

    • burst:应对突发请求时额外允许的请求数目。

    • maxQueueingTimeoutMs:匀速排队模式下的最长排队时间,单位是毫秒,仅在匀速排队模式下生效。、

    • paramItem:参数限流配置。若不提供,则代表不针对参数进行限流,该网关规则将会被转换成普通流控规则;否则会转换成热点规则。其中的字段:

      • parseStrategy:从请求中提取参数的策略,目前支持提取来源 IP(PARAM_PARSE_STRATEGY_CLIENT_IP)、Host(PARAM_PARSE_STRATEGY_HOST)、任意 Header(PARAM_PARSE_STRATEGY_HEADER)和任意 URL 参数(PARAM_PARSE_STRATEGY_URL_PARAM)四种模式。

      • fieldName:若提取策略选择 Header 模式或 URL 参数模式,则需要指定对应的 header 名称或 URL 参数名称。

      • pattern:参数值的匹配模式,只有匹配该模式的请求属性值会纳入统计和流控;若为空则统计该请求属性的所有值。(1.6.2 版本开始支持)

      • matchStrategy:参数值的匹配策略,目前支持精确匹配(PARAM_MATCH_STRATEGY_EXACT)、子串匹配(PARAM_MATCH_STRATEGY_CONTAINS)和正则匹配(PARAM_MATCH_STRATEGY_REGEX)。(1.6.2 版本开始支持)

    用户可以通过 GatewayRuleManager.loadRules(rules) 手动加载网关规则,或通过 GatewayRuleManager.register2Property(property) 注册动态规则源动态推送(推荐方式)。

    自定义限流的处理方法:

    ​ 默认被限流的时候会报下面这个错:

    image-20210218211015679

    如果我们想在被限流的时候返回自定义的响应,可以在 GatewayCallbackManager 注册回调进行定制:

    • setBlockHandler:注册函数用于实现自定义的逻辑处理被限流的请求,对应接口为 BlockRequestHandler。默认实现为 DefaultBlockRequestHandler,当被限流时会返回类似于下面的错误信息:Blocked by Sentinel: FlowException

    sentinel控制台界面展示:

    api管理:这里对应的就是ApiDefinition的配置

    image-20210218164517707

    image-20210218164617225

    流控规则:这里对应的就是GatewayFlowRule的配置

    image-20210218172321807

    image-20210218172339222

    api类型:

    • Route ID: spring cloud gateway里面定义的routesId的,在applicaiton.properties中的spring.cloud.gateway.routes里面。比如我们的配置:image-20210218211929544

      所以我们这里可以设置route ID是名字叫: web,user。

    • API 分组: ApiDefinition定义的资源。

    网关的降级规则问题处理

    一个请求的流程图如下:

    image-20210218213451969

    那么网关能知道下游客户端报错了。并且触发熔断降级吗?

    答:不知道。所以无法触发熔断降级。

    解决思路:

    image-20210218214802497

    代码如下:

    @Configuration
    public class SentinelGlobalFilter implements GlobalFilter , Ordered {
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            ServerHttpResponse originalResponse = exchange.getResponse();
            ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
    
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    // get match route id
                    Route route = (Route) exchange.getAttributes().get(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
                    String id = route.getId();
                    // 500 error -> degrade
                    if (originalResponse.getRawStatusCode() == 500) {
                        Entry entry = null;
                        try {
                            // 0 token
                            entry = SphU.entry(id);
                            Tracer.traceEntry(new Exception("error"), entry);
                        } catch (BlockException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
    
                        } finally {
                            if (entry != null){
                                entry.close();
    
                            }
                        }
                    }
                    return super.writeWith(body);
                }
            };
            // replace response with decorator
            return chain.filter(exchange.mutate().response(decoratedResponse).build());
    
    
        }
    
    
        @Override
        public int getOrder() {
            return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1;
        }
    }
    
    

    demo地址:

    地址:https://gitee.com/gzgyc/sentinel-demo.git

    模块名:sentinel-gateway

  • 相关阅读:
    sort
    Sicily--17956. Maximum Multiple
    代码1005
    487-3279的解法实例
    487-3279另一种解法
    487-3279
    人工智能--识别句子
    1003-Hangover
    推荐书单(转自GITHUB)
    转自微信号:测试那点事
  • 原文地址:https://www.cnblogs.com/dabenxiang/p/14413702.html
Copyright © 2020-2023  润新知