SpringCloudAlibaba Gateway(三)-整合Sentinel功能路由维度、API维度进行流控

这篇具有很好参考价值的文章主要介绍了SpringCloudAlibaba Gateway(三)-整合Sentinel功能路由维度、API维度进行流控。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Gateway整合Sentinel

​ 前面使用过Sentinel组件对服务提供者、服务消费者进行流控、限流等操作。除此之外,Sentinel还支持对Gateway、Zuul等主流网关进行限流。

​ 自sentinel1.6.0版开始,Sentinel提供了Gateway的适配模块,能针对路由(route)和自定义API分组两个维度进行限流。

路由维度

路由维度是指配置文件中的路由条目,资源名是对应的routeId,相比自定义API维度,这是比较粗粒度的。看下如何实现:

  1. 导入Sentinel组件为Gateway提供的适配依赖包,在pom.xml中导入依赖

    <!--sentinel为gateway提供的适配包-->
    <dependency>
        <groupId>com.alibaba.csp</groupId>
        <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
    </dependency>
    
  2. 增加配置类SentinelRouteConfiguration,实例化SentinelGatewayFilterSentinelBlockExceptionHandler对象,初始化限流规则

    @Configuration  // 配置类
    public class SentinelRouteConfiguration {   // 路由限流规则配置类
    
        private final List<ViewResolver> viewResolvers;
    
        private final ServerCodecConfigurer serverCodecConfigurer;
    
    
        public SentinelRouteConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) {
            this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
            this.serverCodecConfigurer = serverCodecConfigurer;
        }
    
        @PostConstruct
        public void initGatewayRules() {    // 初始化限流规则
            Set<GatewayFlowRule> rules = new HashSet<>();
            GatewayFlowRule gatewayFlowRule = new GatewayFlowRule("user_route");    // 资源名(gateway中的路由id)
            gatewayFlowRule.setCount(1);    // 限流阈值
            gatewayFlowRule.setIntervalSec(1);  // 统计时间窗口,默认1s
    
            rules.add(gatewayFlowRule);
            GatewayRuleManager.loadRules(rules);    // 载入规则
        }
    
        @PostConstruct
        public void initBlockHandlers() {    // 限流后的响应
            BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) -> {
                Map<String, Object> result = new HashMap<>();
                result.put("code", "0");
                result.put("message", "您已被限流");
                return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON_UTF8).body(BodyInserters.fromObject(result));
            };
    
            GatewayCallbackManager.setBlockHandler(blockRequestHandler);    // 设置限流响应
        }
    
        @Bean
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
            return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
        }
    
        @Bean
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public GlobalFilter sentinelGatewayFilter() {   // 初始化限流过滤器
            return new SentinelGatewayFilter();
        }
    
    }
    

    注意:Gateway限流是通过Filter实现的,主要是注入SentinelGatewayFilter实例和SentinelGatewayBlockExceptionHandler实例

  3. 在yml中,设置两个route,user_routeshop_route,上面主要是对user_route限流了,着重看下

    server:
      port: 8083
    
    spring:
      application:
        name: gateway   # 服务名
    
      cloud:
        nacos:
          discovery:
            server-addr: localhost:8848 # nacos地址
        gateway:
          routes: # 路由,可配置多个
          - id: user_route  # 路由id,唯一即可,默认UUID
            uri: lb://user  # 路由地址(匹配成功后的服务地址) user是用户服务的服务名称
            order: 1  # 路由优先级,默认0,越低优先级越高
            predicates:
            - Path=/user/**   # 断言,匹配规则
    
          - id: shop_route  # 路由id,唯一即可,默认UUID
            uri: lb://shop  # 路由地址(匹配成功后的服务地址) shop是用户服务的服务名称
            order: 1  # 路由优先级,默认0,越低优先级越高
            predicates:
            - Path=/shop/**   # 断言,匹配规则
    
  4. 启动服务开始调试

    SpringCloudAlibaba Gateway(三)-整合Sentinel功能路由维度、API维度进行流控,SpringCloud,SpringBoot,Java,gateway,sentinel,java

    成功完成路由级别的限流,那么后面看看API维度的限流

自定义API维度

​ 上面那种限流方式可以看出灵活性不够高。自定义的API维度可以利用Sentinel提供的API自定义分组来进行限流。相比路由维度,这是一种更加细粒度的限流方式。

实现

  1. 导入Gateway的适配包

    <!--sentinel为gateway提供的适配包-->
    <dependency>
        <groupId>com.alibaba.csp</groupId>
        <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
    </dependency>
    
  2. 依然是实例化SentinelGatewayFilterSentinelBlockExceptionHandler对象,初始化限流规则,定义API分组

    @Configuration  // 配置类
    public class SentinelRouteConfiguration {   // 路由限流规则配置类
    
        private final List<ViewResolver> viewResolvers;
    
        private final ServerCodecConfigurer serverCodecConfigurer;
    
    
        public SentinelRouteConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) {
            this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
            this.serverCodecConfigurer = serverCodecConfigurer;
        }
    
        @PostConstruct
        public void initGatewayRules() {    // 初始化限流规则
            Set<GatewayFlowRule> rules = new HashSet<>();
            GatewayFlowRule gatewayFlowRule = new GatewayFlowRule("user_api");    // 资源名,api分组的名称(自定义)
            gatewayFlowRule.setCount(1);    // 限流阈值
            gatewayFlowRule.setIntervalSec(1);  // 统计时间窗口,默认1s
    
            rules.add(gatewayFlowRule);
            GatewayRuleManager.loadRules(rules);    // 载入规则
        }
    
        @PostConstruct
        public void initCustomizedApis() {
            Set<ApiDefinition> apiDefinitions = new HashSet<>();
            ApiDefinition apiDefinition = new ApiDefinition("user_api") // 定义 api分组
                    .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                            add(new ApiPathPredicateItem()
                                    .setPattern("/user/group/**")	// 路径匹配规则
                                    .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX)); // 匹配策略,前缀匹配
                        }});
            apiDefinitions.add(apiDefinition);
    
            GatewayApiDefinitionManager.loadApiDefinitions(apiDefinitions); // 载入API分组定义
    
        }
    
        @PostConstruct
        public void initBlockHandlers() {    // 限流后的响应
            BlockRequestHandler blockRequestHandler = (serverWebExchange, throwable) -> {
                Map<String, Object> result = new HashMap<>();
                result.put("code", "0");
                result.put("message", "您已被限流");
                return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON_UTF8).body(BodyInserters.fromObject(result));
            };
    
            GatewayCallbackManager.setBlockHandler(blockRequestHandler);    // 设置限流响应
        }
    
        @Bean
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
            return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
        }
    
        @Bean
        @Order(Ordered.HIGHEST_PRECEDENCE)
        public GlobalFilter sentinelGatewayFilter() {   // 初始化限流过滤器
            return new SentinelGatewayFilter();
        }
    
    }
    

    唯一要注意的是:路由匹配规则如果是单一的一个具体接口,不是匹配符,那么后面的匹配策略就没有必要再去配置了(setMatchStrategy()方法)

  3. 定义一个/user/group/findById接口

    @RequestMapping("/user/group/findById")
    public String findGById(@RequestParam("id") Integer id) {
        return userInfo.getOrDefault(id, null);
    }
    
  4. 启动调用测试

    SpringCloudAlibaba Gateway(三)-整合Sentinel功能路由维度、API维度进行流控,SpringCloud,SpringBoot,Java,gateway,sentinel,java

    可以看到配置的没有问题,满足/user/group/**规则的请求,有被限流到

超时配置

Gateway默认没有超时的限制,也就是数据什么时候返回,就等待到什么时候。如果不想等待,可以增加对超时的配置

gateway:
  httpclient:
    connect-timeout: 5000 # 建立连接时间限制,单位毫秒
    response-timeout: 4s  # 响应时间的时间限制

尝试下,接口睡眠5s,再次调用

curl localhost:8083/user/group/findById?id=1
{"timestamp":"2023-09-02T00:59:47.184+00:00","path":"/user/group/findById","status":504,"error":"Gateway Timeout","requestId":"7f5ff558-1"}

被告知504,超时了~

CORS配置

涉及到前后端分离的跨域请求时,浏览器访问后端地址通常提示No Access-Control-Allow-Origin header is present on the requested resource

可以在gateway中增加跨域配置,或者前端去配置都可以,自行协商。

cloud:
  nacos:
    discovery:
      server-addr: localhost:8848 # nacos地址
  gateway:
    httpclient:
      connect-timeout: 5000 # 建立连接时间限制,单位毫秒
      response-timeout: 4s  # 响应时间的时间限制
    globalcors:
      cors-configurations: 
        '[/**]':
          allowedOrigins: "*" # 允许的来源
          allowedMethods: "*" # 允许的方法
          allowedHeaders: "*" # 允许的请求头  *表示所有

通常情况下,也可以不是按照全部允许来做,按照你的项目实际开发需求搞就行了。文章来源地址https://www.toymoban.com/news/detail-691629.html

到了这里,关于SpringCloudAlibaba Gateway(三)-整合Sentinel功能路由维度、API维度进行流控的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring Cloud 之 Sentinel简介与GATEWAY整合实现

    随着微服务的流行,服务和服务之间的稳定性变得越来越重要。Sentinel 是面向分布式服务架构的流量控制组件,主要以流量为切入点,从限流、流量整形、熔断降级、系统负载保护、热点防护等多个维度来帮助开发者保障微服务的稳定性。 熔断 微服务架构的系统通常会包含

    2024年02月19日
    浏览(32)
  • SpringCloud之Gateway整合Sentinel服务降级和限流

    1.下载Sentinel.jar可以图形界面配置限流和降级规则 地址:可能需要翻墙 下载jar文件 2.引入maven依赖 3.写个自动注入Resource的过滤器类(可以不写注解直接使用) 4.写配置文件 application.properties 5.cmd命令行启动jar文件访问localhost:18080页面,自己设置QPS java -jar -server.port=18080 sentinel-dash

    2024年02月07日
    浏览(32)
  • Spring Cloud Gateway 整合 sentinel 实现流控熔断

            在微服务架构中,网关层可以屏蔽外部服务直接对内部服务进行调用,对内部服务起到隔离保护的作用,网关限流,顾名思义,就是通过网关层对服务进行限流,从而达到保护后端服务的作用。         Sentinel 从 1.6.0 版本开始就提供了 Spring Cloud Gateway 的适配

    2023年04月23日
    浏览(34)
  • 【SpringCloudAlibaba】Sentinel使用

    https://github.com/alibaba/Sentinel 中文: https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D https://sentinelguard.io/zh-cn/docs/introduction.html 服务雪崩 服务降级 服务熔断 服务限流 https://github.com/alibaba/Sentinel/releases Sentinel采用的懒加载 直接(默认) 资源名:默认rest路径名 来源:默认 关联 当与

    2024年02月10日
    浏览(29)
  • SpringCloudAlibaba之Sentinel介绍

    Sentinel 是阿里开源的一款面向分布式、多语言异构化服务架构的流量治理组件。 主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。 上面两句话来自 Sentinel 官网的自我介绍

    2024年02月09日
    浏览(30)
  • SpringCloudAlibaba之Sentinel(一)流控篇

    为什么使用Sentinel,这是一个高可用组件,为了使我们的微服务高可用而生 我们的服务会因为什么被打垮? 一,流量激增    缓存未预热,线程池被占满 ,无法响应 二,被其他服务拖垮,比如第三方的接口响应慢 三,异常没有处理:缓存击穿,缓存穿透等等 总之而言:系

    2024年02月14日
    浏览(26)
  • springCloudAlibaba集成sentinel实战(超详细)

    Sentinel是阿里开源的项目,提供了流量控制、熔断降级、系统负载保护等多个维度来保障服务之间的稳定性。 分布式系统的流量防卫兵: 随着微服务的普及,服务调用的稳定性变得越来越重要。Sentinel以“流量”为切入点,在流量控制、断路、负载保护等多个领域开展工作,

    2024年04月15日
    浏览(33)
  • 4.springcloudalibaba sentinel v1.8.6版本服务搭建

    前面完成了gateway项目部署并且测试,现在部署搭建sentinel服务并且测试。 下载地址 这里选择的是目前最新的sentinel版本 直接下载启动jar包,使用命令安装服务 使用设置的账号密码登录如下图所示启动成功 完整pom如下 完整的配置如下 启动服务后,查看控制台,发现server服务

    2024年02月07日
    浏览(25)
  • 基于SpringCloudAlibaba+Sentinel的分布式限流设计

    胡弦,视频号2023年度优秀创作者,互联网大厂P8技术专家,Spring Cloud Alibaba微服务架构实战派(上下册)和RocketMQ消息中间件实战派(上下册)的作者,资深架构师,技术负责人,极客时间训练营讲师,四维口袋KVP最具价值技术专家,技术领域专家团成员,2021电子工业出版社年度优

    2024年04月22日
    浏览(25)
  • 重写RuoYi-Cloud所有功能 整合 SpringCloudAlibaba Dubbo Mybatis-Plus MQ OSS ES Xxl-Job Docker 全方位升级 定期同步

    转载于:https://blog.csdn.net/weixin_40461281/article/details/122837923 RuoYi-Cloud-Plus  微服务通用权限管理系统  重写 RuoYi-Cloud 全方位升级(不兼容原框架) 系统演示: 传送门 分布式集群版本(功能一致) 功能介绍 使用技术 文档地址 特性注意事项 微服务权限管理系统 RuoYi-Cloud-Plus RuoYi-Clo

    2024年02月08日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包