【SpringCloud-Alibaba系列教程】11.gateway与sentinel组合

简介: 在之前,我们教程已经写了一部分关于sentinel限流的方式,主要是针对于某个微服务本身进行限流,后来我们引入网关的概念,现在我们结合gateway与sentinel进行限流,主要是从一下两个纬度,第一个就是路由维度,另一种就是分组维度,下面我们根据不同维度进行实战。

引入问题
在之前,我们教程已经写了一部分关于sentinel限流的方式,主要是针对于某个微服务本身进行限流,后来我们引入网关的概念,现在我们结合gateway与sentinel进行限流,主要是从一下两个纬度,第一个就是路由维度,另一种就是分组维度,下面我们根据不同维度进行实战。

我们开始吧
首先引入pom相关文件

  <!--网关路由限流-->

       <dependency>

           <groupId>com.alibaba.csp</groupId>

           <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>

       </dependency>

然后编写相关配置类
image.png

我们是基于sentinel的所以我们需要初始化这样一个。

//初始化限流过滤器
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public GlobalFilter sentinelGatewayFilter() {
    return new SentinelGatewayFilter();
}

然后就是编写配置类了
image.png

我们多次刷新就可以看到了
image.png

另外一个就是分组限流,主要就是通过将不同的api进行分组,指定一些接口限流。
直接上代码

/**
 * 配置限流规则
 */
@PostConstruct
private void initGatewayRules() {
    //Set<GatewayFlowRule> rules = new HashSet<>();
    //rules.add(new GatewayFlowRule("product_route")//资源名称对应的路由id
    //        .setCount(1) // 限流阈值
    //        .setIntervalSec(1) // 统计时间窗口,单位是秒,默认是 1 秒
    //);
    //GatewayRuleManager.loadRules(rules);
    Set<GatewayFlowRule> rules = new HashSet<>();
    rules.add(new GatewayFlowRule("product_api1").setCount(1).setIntervalSec(1));
    rules.add(new GatewayFlowRule("product_api2").setCount(1).setIntervalSec(1));
    GatewayRuleManager.loadRules(rules);
}
//配置限流的异常处理器
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
    // Register the block exception handler for Spring Cloud Gateway.
    return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
}
//自定义限流异常页面
@PostConstruct
public void initBlockHandlers() {
    BlockRequestHandler blockRequestHandler = new BlockRequestHandler(){
        @Override
        public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
            Map map = new HashMap();
            map.put("code",0);
            map.put("messgae","接口被限流了...");
            return  ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON_UTF8).
                    body(BodyInserters.fromObject(map));
        }
    };
    GatewayCallbackManager.setBlockHandler(blockRequestHandler);
}
//自定义API分组
@PostConstruct
private void initCustomizedApis() {
    Set<ApiDefinition> definitions = new HashSet<>();
    ApiDefinition api1 = new ApiDefinition("product_api1")
            .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                ///product-serv/product/api1开头的请求
                add(new ApiPathPredicateItem().setPattern("/product-serv/product/api1/**")
                        .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
            }});
    ApiDefinition api2 = new ApiDefinition("product_api2")
            .setPredicateItems(new HashSet<ApiPredicateItem>() {{
                ///product-serv/product/api2
                add(new ApiPathPredicateItem().setPattern("/product-serv/product/api2/demo1"));
            }});
    definitions.add(api1);
    definitions.add(api2);
    GatewayApiDefinitionManager.loadApiDefinitions(definitions);
}

主要就是这样的两种方式进行限流。
到此,我们这一章的sentinel与gateway组合就完成了
后期会在这个项目上不断添加,喜欢的请点个start~
项目源码参考一下分支220226_xgc_gatewayAndSentinel
Gitee:https://gitee.com/coderxgc/springcloud-alibaba
GitHub:https://github.com/coderxgc/springcloud-alibaba

目录
相关文章
|
7月前
|
负载均衡 监控 Java
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
本文详细介绍了 Spring Cloud Gateway 的核心功能与实践配置。首先讲解了网关模块的创建流程,包括依赖引入(gateway、nacos 服务发现、负载均衡)、端口与服务发现配置,以及路由规则的设置(需注意路径前缀重复与优先级 order)。接着深入解析路由断言,涵盖 After、Before、Path 等 12 种内置断言的参数、作用及配置示例,并说明了自定义断言的实现方法。随后重点阐述过滤器机制,区分路由过滤器(如 AddRequestHeader、RewritePath、RequestRateLimiter 等)与全局过滤器的作用范围与配置方式,提
Spring Cloud Gateway 全解析:路由配置、断言规则与过滤器实战指南
|
6月前
|
缓存 JSON NoSQL
别再手写过滤器!SpringCloud Gateway 内置30 个,少写 80% 重复代码
小富分享Spring Cloud Gateway内置30+过滤器,涵盖请求、响应、路径、安全等场景,无需重复造轮子。通过配置实现Header处理、限流、重试、熔断等功能,提升网关开发效率,避免代码冗余。
626 1
|
9月前
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
657 0
|
12月前
|
SpringCloudAlibaba Java Nacos
尚硅谷SpringCloud教程 笔记
本文介绍了基于Spring Cloud Alibaba构建的cloud-demo工程创建步骤,包括父模块及子模块的配置。父模块采用pom打包方式,定义了Java 8、Spring Boot 2.4.2、Spring Cloud 2020.0.1及Spring Cloud Alibaba 2021.1版本。包含三个主要模块:services(依赖Nacos)、service-order和service-product(均依赖spring-boot-starter-web)。同时提供了discoveryClient的测试代码,展示服务发现功能的实现与验证过程。
702 12
尚硅谷SpringCloud教程 笔记
|
10月前
|
缓存 监控 Java
说一说 SpringCloud Gateway 堆外内存溢出排查
我是小假 期待与你的下一次相遇 ~
1310 5
|
10月前
|
Java API Nacos
|
JSON Java API
利用Spring Cloud Gateway Predicate优化微服务路由策略
Spring Cloud Gateway 的路由配置中,`predicates`​(断言)用于定义哪些请求应该匹配特定的路由规则。 断言是Gateway在进行路由时,根据具体的请求信息如请求路径、请求方法、请求参数等进行匹配的规则。当一个请求的信息符合断言设置的条件时,Gateway就会将该请求路由到对应的服务上。
1439 69
利用Spring Cloud Gateway Predicate优化微服务路由策略
|
前端开发 Java Nacos
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
本文介绍了如何使用Spring Cloud Alibaba 2023.0.0.0技术栈构建微服务网关,以应对微服务架构中流量治理与安全管控的复杂性。通过一个包含鉴权服务、文件服务和主服务的项目,详细讲解了网关的整合与功能开发。首先,通过统一路由配置,将所有请求集中到网关进行管理;其次,实现了限流防刷功能,防止恶意刷接口;最后,添加了登录鉴权机制,确保用户身份验证。整个过程结合Nacos注册中心,确保服务注册与配置管理的高效性。通过这些实践,帮助开发者更好地理解和应用微服务网关。
2334 0
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
|
SpringCloudAlibaba JavaScript Dubbo
【SpringCloud Alibaba系列】Dubbo dubbo-admin安装教程篇
本文介绍了 Dubbo-Admin 的安装和使用步骤。Dubbo-Admin 是一个前后端分离的项目,前端基于 Vue,后端基于 Spring Boot。安装前需确保开发环境(Windows 10)已安装 JDK、Maven 和 Node.js,并在 Linux CentOS 7 上部署 Zookeeper 作为注册中心。
4061 1
【SpringCloud Alibaba系列】Dubbo dubbo-admin安装教程篇
|
JavaScript Java Kotlin
深入 Spring Cloud Gateway 过滤器
Spring Cloud Gateway 是新一代微服务网关框架,支持多种过滤器实现。本文详解了 `GlobalFilter`、`GatewayFilter` 和 `AbstractGatewayFilterFactory` 三种过滤器的实现方式及其应用场景,帮助开发者高效利用这些工具进行网关开发。
2093 1
下一篇
开通oss服务