【SpringCloud Alibaba】(九)学习 Gateway 服务网关

devtools/2024/9/23 14:43:38/

目录

  • 1、网关概述
    • 1.1、没有网关的弊端
    • 1.2、引入 API 网关
  • 2、主流的 API 网关
    • 2.1、Nginx+Lua
    • 2.2、Kong 网关
    • 2.3、Zuul 网关
    • 2.4、Apache Shenyu 网关
    • 2.5、SpringCloud Gateway 网关
  • 3、SpringCloud Gateway 网关
    • 3.1、Gateway 概述
    • 3.2、Gateway 核心架构
  • 4、项目整合 SpringCloud Gateway 网关
    • 4.1、新建网关模块
    • 4.2、初步整合 Gateway
  • 5、网关 Gateway 整合 Nacos
  • 6、网关 Gateway 整合 Nacos 最简配置
  • 7、网关 Gateway 整合 Sentinel 限流
    • 7.1、实现 route 维度限流
    • 7.2、实现自定义 API 分组维度限流
  • 代码地址

1、网关概述

当采用分布式、微服务的架构模式开发系统中,服务网关是整个系统中必不可少的一部分。

1.1、没有网关的弊端

当一个系统使用分布式、微服务架构后,系统会被拆分为一个个小的微服务,每个微服务专注一个小的业务。那么,客户端如何调用这么多微服务的接口呢?如果不做任何处理,没有服务网关,就只能在客户端记录下每个微服务的每个接口地址,然后根据实际需要去调用相应的接口。如下:

在这里插入图片描述

这种直接使用客户端记录并管理每个微服务的每个接口的方式,存在着太多的问题。比如,这里我列举几个常见的问题:

  • 由客户端记录并管理所有的接口缺乏安全性。
  • 由客户端直接请求不同的微服务,会增加客户端程序编写的复杂性。
  • 涉及到服务认证与鉴权规则时,需要在每个微服务中实现这些逻辑,增加了代码的冗余性。
  • 客户端调用多个微服务,由于每个微服务可能部署的服务器和域名不同,存在跨域的风险。
  • 当客户端比较多时,每个客户端上都管理和配置所有的接口,维护起来相对比较复杂

1.2、引入 API 网关

API 网关,其实就是整个系统的统一入口。网关会封装微服务的内部结构,为客户端提供统一的入口服务,同时,一些与具体业务逻辑无关的通用逻辑可以在网关中实现,比如认证、授权、路由转发、限流、监控等。引入 API 网关后,如下所示:

在这里插入图片描述

可以看到,引入 API 网关后,客户端只需要连接 API 网关,由 API 网关根据实际情况进行路由转发,将请求转发到具体的微服务,同时,API 网关会提供认证、授权、限流和监控等功能。

2、主流的 API 网关

当系统采用分布式、微服务的架构模式后,API 网关就成了整个系统不可分割的一部分。业界通过不断的探索与创新,实现了多种API网关的解决方案。目前,比较主流的API网关有:Nginx + Lua、Kong 网关、Zuul 网关、Apache Shenyu 网关、SpringCloud Gateway 网关。

2.1、Nginx+Lua

Nginx 的一些插件本身就实现了限流、缓存、黑白名单和灰度发布,再加上 Nginx 的反向代理和负载均衡,能够实现对服务接口的负载均衡和高可用。而 Lua 语言可以实现一些简单的业务逻辑,Nginx 又支持 Lua 语言。所以,可以基于 Nginx + Lua 脚本实现网关。

2.2、Kong 网关

Kong 网关基于 Nginx 与 Lua 脚本开发,性能高,比较稳定,提供多个限流、鉴权等插件,这些插件支持热插拔,开箱即用。Kong 网关提供了管理页面,但是,目前基于 Kong 网关二次开发比较困难。

2.3、Zuul 网关

Zuul 网关是 Netflix 开源的网关,功能比较丰富,主要基于 Java 语言开发,便于在 Zuul 网关的基础上进行二次开发。但是 Zuul 网关无法实现动态配置规则,依赖的组件相对来说也比较多,在性能上不如 Nginx。

2.4、Apache Shenyu 网关

Dromara 社区开发的网关框架,ShenYu 的前名是 soul,最近正式加入了 Apache 的孵化器,因此改名为 ShenYu。其是一个异步的,高性能的,跨语言的,响应式的 API 网关,并在此基础上提供了非常丰富的扩展功能:

  • 支持各种语言(http 协议),支持 Dubbo、Spring-Cloud、Grpc、Motan、Sofa、Tars 等协议。
  • 插件化设计思想,插件热插拔,易扩展。
  • 灵活的流量筛选,能满足各种流量控制。
  • 内置丰富的插件支持,鉴权,限流,熔断,防火墙等等。
  • 流量配置动态化,性能极高。
  • 支持集群部署,支持 A/B Test,蓝绿发布

2.5、SpringCloud Gateway 网关

Spring 为了替换 Zuul 而开发的网关,SpringCloud Alibaba 技术栈中,并没有单独实现网关的组件。在后续的案例实现中,我们会使用 SpringCloud Gateway 实现网关功能。

3、SpringCloud Gateway 网关

3.1、Gateway 概述

Spring Cloud Gateway 是 Spring 公司基于 Spring 5.0, Spring Boot 2.0 和 Project Reactor 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式

Geteway 作为 Spring Cloud 生态系统中的网关,目标是替代 Zuul,在 Spring Cloud2.0 以上版本中,没有对新版本的 Zuul 2.0 以上最新高性能版本进行集成,仍然还是使用的 Zuul 1.x 非 Reactor 模式的老版本

而为了提升网关性能,Spring Cloud Gateway 是基于 WebFlux 框架实现的,而 WebFlux 框架底
层则使用了高性能的 Reactor 模式通信框架 Netty。

Gateway 的目标提供统一的路由方式且基于 Filter 链的方式提供了网关基本的功能,例如:
安全,监控/指标,和限流

Spring Cloud Gateway 使用的 Webflux 中的 reactor-netty 响应式编程组件,底层使用 Netty 通讯框架

3.2、Gateway 核心架构

客户端请求到 Gateway 网关,会先经过 Gateway Handler Mapping 进行请求和路由匹配。匹配成功后再发送到 Gateway Web Handler 处理,然后会经过特定的过滤器链,经过所有前置过滤后,会发送代理请求。请求结果返回后,最后会执行所有的后置过滤器。如下图:

在这里插入图片描述

SpringCloud Gateway 的主要流程为:客户端请求会先打到 Gateway,具体的讲应该是 DispacherHandler(因为 Gateway 引入了 WebFlux,作用可以类比 MVC 的 DispacherServlet),Gateway 根据用户的请求找到相应的 HandlerMapping,请求和具体的 handler 之间有一个映射关系,网关会对请求进行路由,handler 会匹配到 RoutePredicateHandlerMapping,匹配请求对应的 Route,然后到达 Web 处理器,WebHandler 代理了一系列网关过滤器和全局过滤器的实例,这些过滤器可以对请求和响应进行修改,最后由代理服务完成用户请求,并将结果返回。

4、项目整合 SpringCloud Gateway 网关

4.1、新建网关模块

在项目中新建 shop-gateway 模块,新增网关模块后项目的结构如下图所示:

在这里插入图片描述

4.2、初步整合 Gateway

1、在服务网关 shop-gateway 模块的 pom.xml 文件中添加如下依赖:

<dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId></dependency>
</dependencies>

2、在服务网关 shop-gateway 模块的 resources 目录下新建 application.yml 文件,并在文件中添加如下配置信息:

server:port: 10001
spring:application:name: server-gatewaycloud:gateway:globalcors:                       # 配置跨域cors-configurations:'[/**]':allowedOrigins: "*"allowedMethods: "*"allowCredentials: trueallowedHeaders: "*"routes:                           # 路由配置【数组】- id: user-gateway              # 路由 iduri: http://localhost:8060    # 路由地址order: 1                      # 路由排序,数字越大,优先级越低predicates:                   # 断言配置/路由转发的条件【数组】- Path=/server-user/**      # 路径匹配:当客户端请求的路径满足 Path 的规则时,进行路由转发操作filters:                      # 过滤器配置【数组】- StripPrefix=1             # 去掉前缀:去掉客户端请求的路径中的第一个路径,即去掉 /server-user- id: product-gatewayuri: http://localhost:8070order: 1predicates:- Path=/server-product/**filters:- StripPrefix=1- id: order-gatewayuri: http://localhost:8080order: 1predicates:- Path=/server-order/**filters:- StripPrefix=1

我们重点来看下 spring.cloud.gateway 节点下的配置。

  • globalcors:此节点下的配置是为了解决 SpringCloud Gateway 跨域的问题。
  • routes:表示一个路由数组,可以在此节点下配置多个路由信息。
  • id:当前路由的唯一标识。
  • order:路由的优先级,数字越小表示优先级越高。
  • predicates:网关断言,也就是路由转发的条件,也是一个数组,可以配置多个路由转发条件。
  • Path:当客户端请求的路径满足 Path 的规则时,进行路由转发操作。
  • filters:网关过滤器,在过滤器中可以修改请求的参数和 header 信息,以及响应的结果和 header 信息,网关过滤器也是一个数组,可以配置多个过滤规则。
  • StripPrefix:网关在进行路由转发之前,会去掉 1 层访问路径

3、在服务网关 shop-gateway 模块的 com.zzc 包下新建 ShopGatewayApplication 类,表示服务网关的启动类,源码如下所示:

@SpringBootApplication
public class ShopGatewayApplication {public static void main(String[] args) {SpringApplication.run(ShopGatewayApplication.class, args);}}

4、由于之前项目中整合了 Nacos 和 Sentinel,所以,在启动项目前,要分别启动 Nacos 和 Sentinel
5、分别启动用户微服务、商品微服务、订单微服务和服务网关。
6、通过服务网关访问用户微服务,在浏览器中输入 http://localhost:10001/server-user/user/get/1001 ,如下所示:

在这里插入图片描述

直接通过用户微服务访问:http://localhost:8060/user/get/1001

7、产品微服务、订单微服务以此类推

5、网关 Gateway 整合 Nacos

在初步整合 SpringCloud Gateway 中,我们在服务网关模块的 application.yml 文件中 硬编码配置了服务转发的地址,如下所示:

  • 硬编码用户微服务地址
uri: http://localhost:8060
  • 硬编码商品微服务地址
uri: http://localhost:8070
  • 硬编码订单微服务地址
uri: http://localhost:8080

这里,我们将网关整合 Nacos 实现从 Nacos 注册中心获取转发的服务地址

1、在服务网关 shop-gateway 模块的 pom.xml 文件中继续添加如下依赖:

<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2、在服务网关 shop-gateway 模块的启动类上添加 @EnableDiscoveryClient 注解,如下所示:

@SpringBootApplication
@EnableDiscoveryClient
public class ShopGatewayApplication {// ...
}

3、将 application.yml 备份一份,命名为 application-simple.yml,并修改 application.yml配置文件,修改后的文件如下所示:

server:port: 10001
spring:application:name: server-gatewaycloud:nacos:discovery:server-addr: 127.0.0.1:8848gateway:globalcors:                       # 配置跨域cors-configurations:'[/**]':allowedOrigins: "*"allowedMethods: "*"allowCredentials: trueallowedHeaders: "*"routes:                           # 路由配置【数组】- id: user-gateway              # 路由 iduri: lb://server-user         # 路由地址order: 1                      # 路由排序,数字越大,优先级越低predicates:                   # 断言配置/路由转发的条件【数组】- Path=/server-user/**      # 路径匹配:当客户端请求的路径满足 Path 的规则时,进行路由转发操作filters:                      # 过滤器配置【数组】- StripPrefix=1             # 去掉前缀:去掉客户端请求的路径中的第一个路径,即去掉 /server-user- id: product-gatewayuri: lb://server-productorder: 1predicates:- Path=/server-product/**filters:- StripPrefix=1- id: order-gatewayuri: lb://server-orderorder: 1predicates:- Path=/server-order/**filters:- StripPrefix=1discovery:locator:enabled: true                   # 开启服务发现

①:上述配置中增加了 Nacos 相关的配置,如下所示:

spring:cloud:nacos:discovery:server-addr: 127.0.0.1:8848

②:新增了让 SpringCloud Gateway 可以发现 Nacos 中的服务配置,如下所示:

Spring:cloud:gateway:discovery:locator:enabled: true

③:另外,将硬编码的服务转发地址修改成从 Nacos 中按照名称获取微服务地址,并按照负载均衡策略分发

  • 从 Nacos 中获取用户微服务
uri: lb://server-user
  • 从 Nacos 中获取商品微服务
uri: lb://server-product
  • 从 Nacos 中获取订单微服务
uri: lb://server-order

其中,lb 指的是从 Nacos 中按照微服务的名称获取微服务地址,并按照负载均衡的策略分发。使用 lb从 Nacos 中获取微服务时,遵循如下的格式:

lb: //微服务名称

微服务的名称就是各个微服务在 application.yml 文件中配置的服务名称:

spring:application:name: 服务名称

4、分别启动用户微服务、商品微服务、订单微服务和服务网关
5、通过服务网关访问用户微服务,在浏览器中输入http://localhost:10001/server-user/user/get/1001 ,如下所示:

在这里插入图片描述

6、网关 Gateway 整合 Nacos 最简配置

SpringCloud Gateway 整合 Nacos 后,可以不用手动指定其他微服务的名称来从 Nacos 中获取微服务的地址。接下来,我们就来实现 SpringCloud Gateway 网关整合 Nacos 的最简配置。

1、将 application.yml 备份一份,命名为 application-nacos.yml,并修改 application.yml 配置文件,修改后的文件如下所示:

server:port: 10001
spring:application:name: server-gatewaycloud:nacos:discovery:server-addr: 127.0.0.1:8848gateway:globalcors:                       # 配置跨域cors-configurations:'[/**]':allowedOrigins: "*"allowedMethods: "*"allowCredentials: trueallowedHeaders: "*"discovery:locator:enabled: true                 # 开启服务发现

application.yml 文件中,去掉了 spring.cloud.gateway.routes 节点及其下面的所有配置

2、分别启动用户微服务、商品微服务、订单微服务和服务网关
3、通过服务网关访问用户微服务,在浏览器中输入http://localhost:10001/server-user/user/get/1001 ,如下所示:

在这里插入图片描述

注意:SpringCloud Gateway 整合 Nacos 最简配置时,通过网关访问微服务的格式如下所示:

http(s)://网关IP:网关端口/访问的目标微服务名称/接口地址

7、网关 Gateway 整合 Sentinel 限流

Sentinel 从 1.6.0 版本开始,提供了 SpringCloud Gateway 的适配模块,并且可以提供两种资源维度的限流,一种是 route 维度;另一种是自定义 API 分组维度

  • route 维度:对 application.yml文件中配置的 spring.cloud.gateway.routes.id 限流,并且资
    源名为 spring.cloud.gateway.routes.id 对应的值。
  • 自定义 API 分组维度:利用 Sentinel 提供的 API 接口来自定义 API 分组,并且对这些 API 分组进行限流。

7.1、实现 route 维度限流

1、在服务网关 shop-gateway 模块的 pom.xml 文件中添加如下依赖:

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
<dependency><groupId>com.alibaba.csp</groupId><artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
</dependency>

2、在服务网关 shop-gateway 模块中新建 com.zzc.config 包,并在包下新建 GatewayConfig 类。基于 Sentinel 的 Gateway 限流是通过其提供的 Filter 来完成的,使用时只需注入对应的SentinelGatewayFilter 实例以及 SentinelGatewayBlockExceptionHandler 实例即可。

GatewayConfig 类的源代码如下所示:

@Configuration
public class GatewayConfig {private final List<ViewResolver> viewResolvers;private final ServerCodecConfigurer serverCodecConfigurer;@Value("${spring.cloud.gateway.discovery.locator.route-id-prefix}")private String routeIdPrefix;public GatewayConfig(ObjectProvider<List<ViewResolver>> viewResolversProvider, ServerCodecConfigurer serverCodecConfigurer) {this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);this.serverCodecConfigurer = serverCodecConfigurer;}/*** 初始化一个限流的过滤器*/@Bean@Order(Ordered.HIGHEST_PRECEDENCE)public GlobalFilter sentinelGatewayFilter() {return new SentinelGatewayFilter();}@PostConstructpublic void init() {this.initGatewayRules();this.initBlockHandlers();}/*** 配置初始化的限流参数*/private void initGatewayRules() {Set<GatewayFlowRule> rules = new HashSet<>();/*** Sentinel整合SpringCloud Gateway使用的API类型为Route ID类型,也就是基于route维度时,* 由于Sentinel为SpringCloud Gateway网关生成的API名称规则如下:* 生成的规则为:${spring.cloud.gateway.discovery.locator.route-id-prefix}后面直接加上目标微服务的名称,如下所示。* ${spring.cloud.gateway.discovery.locator.route-id-prefix}目标微服务的名称* 其中,${spring.cloud.gateway.discovery.locator.route-id-prefix}是在yml文件中配置的访问前缀** 为了让通过服务网关访问目标微服务链接后,请求链路中生成的API名称与流控规则中生成的API名称一致,以达到启动项目即可实现访问链接的限流效果,* 而无需登录Setinel管理界面手动配置限流规则,可以将* resource参数设置为${spring.cloud.gateway.discovery.locator.route-idprefix}目标微服务的名称** 当然,如果不按照上述配置,也可以在项目启动后,通过服务网关访问目标微服务链接后,在Sentinel管理界面的请求链路中找到对应的API名称所代表的请求链路,* 然后手动配置限流规则。**/// 用户微服务网关// rules.add(this.getGatewayFlowRule("user-gateway"));// 商品微服务网关// rules.add(this.getGatewayFlowRule("product-gateway"));// 订单微服务网关// rules.add(this.getGatewayFlowRule("order-gateway"));//用户微服务网关rules.add(this.getGatewayFlowRule(getResource("server-user")));//商品微服务网关rules.add(this.getGatewayFlowRule(getResource("server-product")));//订单微服务网关rules.add(this.getGatewayFlowRule(getResource("server-order")));//加载规则GatewayRuleManager.loadRules(rules);}private String getResource(String targetServiceName){if (routeIdPrefix == null){routeIdPrefix = "";}return routeIdPrefix.concat(targetServiceName);}private GatewayFlowRule getGatewayFlowRule(String resource){//传入资源名称生成GatewayFlowRuleGatewayFlowRule gatewayFlowRule = new GatewayFlowRule(resource);//限流阈值gatewayFlowRule.setCount(1);//统计的时间窗口,单位为gatewayFlowRule.setIntervalSec(1);return gatewayFlowRule;}/*** 配置限流的异常处理器*/@Bean@Order(Ordered.HIGHEST_PRECEDENCE)public SentinelGatewayBlockExceptionHandlersentinelGatewayBlockExceptionHandler() {return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);}/*** 自定义限流异常页面*/private void initBlockHandlers() {BlockRequestHandler blockRequestHandler = new BlockRequestHandler() {@Overridepublic Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {Map map = new HashMap<>();map.put("code", 1001);map.put("codeMsg", "接口被限流了");return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON_UTF8).body(BodyInserters.fromObject(map));}};GatewayCallbackManager.setBlockHandler(blockRequestHandler);}
}

GatewayConfig 类的源代码看上去比较多,但是都是一些非常简单的方法。

【注意】:Sentinel1.8.4 整合 Gateway 使用的 API 类型为 Route ID 类型时,也就是基于 route 维度时,由于 Sentinel 为 Gateway 网关生成的 API 名称规则如下:${spring.cloud.gateway.discovery.locator.route-id-prefix} 后面直接加上目标微服
务的名称。 其中,${spring.cloud.gateway.discovery.locator.route-id-prefix} 是在 yml 文件中配置的访问前缀。

当然,如果不按照上述配置,也可以在项目启动后,通过服务网关访问目标微服务链接后,在 Sentinel 管理界面的请求链路中找到对应的 API 名称所代表的请求链路,然后手动配置限流规则。

3、将服务网关 shop-gateway 模块的 application.yml 文件备份一份名称为 application-nacos simple.yml 的文件,并将 application.yml 文件的内容修改成如下所示:

server:port: 10001
spring:application:name: server-gatewaymain:allow-bean-definition-overriding: true  # 解决重复注册的问题cloud:nacos:discovery:server-addr: 127.0.0.1:8848sentinel:transport:port: 7777dashboard: 127.0.0.1:8888web-context-unify: false          # 开启 sentinel 的 web 监控eager: true                       # 启动时加载所有规则到 Sentinelgateway:globalcors:                       # 配置跨域cors-configurations:'[/**]':allowedOrigins: "*"allowedMethods: "*"allowCredentials: trueallowedHeaders: "*"discovery:locator:enabled: true                 # 开启服务发现route-id-prefix: gateway-     # 路由 id 前缀

其中:

  • spring.cloud.sentinel.eager:表示程序启动时,流控规则是否立即注册到 Sentinel,配置为
    true 表示立即注册到 Sentinel。
  • spring.cloud.gateway.discovery.locator.route-id-prefix:生成流控规则 API 名称的前缀

4、在 IDEA 中配置启动服务网关 shop-gateway 模块的参数 -Dcsp.sentinel.app.type=1,如下所示:

在这里插入图片描述

如果是在命令行启动网关服务的 Jar 包,则可以使用如下命令:

java -Dcsp.sentinel.app.type=1 shop-gateway.jar

或者在启动类 的 main() 方法中添加一行System.setProperty("csp.sentinel.app.type", "1"); 代码,如下所示:

public class ShopGatewayApplication {public static void main(String[] args) {System.setProperty("csp.sentinel.app.type", "1");SpringApplication.run(ShopGatewayApplication.class, args);}
}

5、分别启动用户微服务、商品微服务、订单微服务和服务网关,启动后会在 Sentinel 管理界面左侧菜单栏中看到 server-gateway 菜单,如下所示:

在这里插入图片描述

server-gateway 菜单下的流控规则子菜单中可以看到网关的流控规则已经注册到 Sentinel,如下所示:

在这里插入图片描述

6、通过服务网关访问用户微服务,在浏览器中输入http://localhost:10001/server-user/user/get/1001 ,不断刷新页面,如下所示:

在这里插入图片描述

可以看到,通过服务网关不断用户订单微服务时,触发了服务限流,并返回了自定义的限流结果数据。

7.2、实现自定义 API 分组维度限流

1、在服务网关 shop-gateway 模块的 com.zzc.config.GatewayConfig 配置类中新增
initCustomizedApis() 方法,初始化 API 管理的信息,源码如下所示:

private void initCustomizedApis() {Set<ApiDefinition> definitions = new HashSet<>();ApiDefinition api1 = new ApiDefinition("user_api1").setPredicateItems(new HashSet<ApiPredicateItem>() {{// 以/server-user/user/api1 开头的请求add(new ApiPathPredicateItem().setPattern("/server-user/user/api1/**").setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));}});ApiDefinition api2 = new ApiDefinition("user_api2").setPredicateItems(new HashSet<ApiPredicateItem>() {{// 以/server-user/user/api2/demo1 完成的url路径匹配add(new ApiPathPredicateItem().setPattern("/server-user/user/api2/demo1"));}});definitions.add(api1);definitions.add(api2);GatewayApiDefinitionManager.loadApiDefinitions(definitions);
}

上述代码中,配置了两个 API 分组,每个 API 分组的规则如下:

  • user_api1 分组:匹配以 /server-user/user/api1 开头的所有请求。
  • user_api2 分组:精确匹配 /server-user/user/api2/demo1

2、在服务网关 shop-gateway 模块的 GatewayConfig 配置类中 init() 方法中调用 initCustomizedApis() 方法,为了避免 route 维度的限流对自定义 API 分组维度的限流产生影响,这里,同时在 init() 方法中注释掉调用 initGatewayRules() 方法,修改后的 init() 方法的代码如下所示:

@PostConstruct
public void init() {//this.initGatewayRules();this.initBlockHandlers();this.initCustomizedApis();
}

3、在用户微服务 shop-userUserController 类中新增四个测试接口,源码如下所示:

@GetMapping(value = "/api1/demo1")
public String api1Demo1(){log.info("访问了api1Demo1接口");return "api1Demo1";
}
@GetMapping(value = "/api1/demo2")
public String api1Demo2(){log.info("访问了api1Demo2接口");return "api1Demo2";
}
@GetMapping(value = "/api2/demo1")
public String api2Demo1(){log.info("访问了api2Demo1接口");return "api2Demo1";
}
@GetMapping(value = "/api2/demo2")
public String api2Demo2(){log.info("访问了api2Demo2接口");return "api2Demo2";
}

4、分别启动用户微服务、商品微服务、订单微服务和服务网关,启动后会在 Sentinel 管理界面左侧菜单栏中看到 server-gateway 菜单,由于我们注释了调用以 route 维度限流的方法,所以,在流控规则里的限流规则为空,如下所示:

在这里插入图片描述

在 API 管理里面会发现我们定义的 API 分组已经自动注册到 Sentinel 中了,如下所示:

在这里插入图片描述

5、在 Sentinel 管理界面的流控规则中,新增网关流控规则,如下所示:

在这里插入图片描述

点击新增网关流控规则后,会弹出新增网关流控规则配置框,按照如下方式为 user_api1 分组配置限流规则:

在这里插入图片描述

点击新增按钮后,按照同样的方式为 user_api2分组配置限流规则。

配置完毕后,在流控规则中的限流规则如下所示:

在这里插入图片描述

6、预期的测试结果如下。

  • 当频繁访问http://localhost:10001/server-user/user/api1/demo1 时会被限流。
  • 当频繁访问http://localhost:10001/server-user/user/api1/demo2 时会被限流。
  • 当频繁访问http://localhost:10001/server-user/user/api2/demo1 时会被限流。
  • 当频繁访问http://localhost:10001/server-user/user/api2/demo2 时不会被限流

注意:只有最后一个不会被限流

7、在浏览器上频繁访问http://localhost:10001/server-user/user/api1/demo1 ,如下所示:

在这里插入图片描述
至此,我们就成功在项目中整合了 SpringCloud Gateway 网关,并通过 Sentinel 整合 SpringCloud
Gateway 实现了网关的限流操作。

代码地址

代码已经上传至码云,码云地址

其中,数据库文件位于 db 文件夹下。


http://www.ppmy.cn/devtools/100125.html

相关文章

Golang学习笔记-Golang中的锁

同步原语和锁 Golang作为一个原生支持用户态的语言&#xff0c;当提到并发进程&#xff0c;多线程的时候&#xff0c;是离不开锁的&#xff0c;锁是一种并发编程中的同步原语&#xff08;Synchronization Primitives&#xff09;&#xff0c;它能保证多个 Goroutine 在访问同一…

STM32GPIO引脚八种工作模式

1. GPIO简述 GPIO&#xff08;General-purpose input/output&#xff09;&#xff0c;通用型输入输出。简单理解就是我们可以控制输入输出的STM32引脚&#xff0c;统称为GPIO。 GPIO存在的意义就是用程序控制或读取它们的输出或输入。 2. 功能描述 每个GPI/O端口有两个32位配…

谷歌、火狐及Edge等浏览器如何使用allWebPlugin中间件响应ActiveX插件事件

allWebPlugin简介 allWebPlugin中间件是一款为用户提供安全、可靠、便捷的浏览器插件服务的中间件产品&#xff0c;致力于将浏览器插件重新应用到所有浏览器。它将现有ActiveX控件直接嵌入浏览器&#xff0c;实现插件加载、界面显示、接口调用、事件回调等。支持Chrome、Firefo…

1.反爬虫机制

一、IP 封锁 网站可以检测请求的IP地址&#xff0c;并封锁那些频繁请求的IP&#xff0c;使其无法访问网站。这是一种常见的反爬虫策略&#xff0c;用于防止单个IP地址对服务器造成过大的负载。 解决办法 &#xff1a; 使用代理IP池以避免IP封锁 // 待补充 二、请求头检测(Us…

【软考】网络安全控制技术

目录 1. 说明2. 防火墙技术3. 加密技术4. 用户识别技术5. 访问控制技术6. 网络反病毒技术7. 网络安全漏洞扫描技术8.入侵检测技术9.例题 1. 说明 1.为了保护网络信息的安全可靠&#xff0c;除了运用法律和管理手段外&#xff0c;还需依靠技术方法来实现。2.网络安全控制技术目…

IT 行业的就业情况

当前&#xff0c;IT 行业的就业情况呈现出以下特点&#xff1a; 1. 需求持续增长&#xff1a;随着数字化转型的加速&#xff0c;各个行业对信息技术的依赖程度不断提高&#xff0c;推动了对 IT 人才的持续需求。特别是在云计算、大数据、人工智能、物联网等新兴领域&#xff…

Vue解决父子组件传值,子组件改变值后父组件的值也改变的问题

vue开发过程中&#xff0c;父组件通过props传值给子组件&#xff0c;子组件在页面展示父组件的值&#xff0c;在操作子组件值以后&#xff0c;即使不点击确定按钮&#xff0c;父组件中的值也发生了变化&#xff0c;但是需求是操作子组件数据以后&#xff0c;必须点击"确定…

海外媒体发稿推荐:约旦著名新闻媒体海外PR新闻稿发布

海外媒体发稿推荐&#xff1a;约旦著名新闻媒体海外PR新闻稿发布 约旦新闻jordannews 约旦新闻jordannews是约旦著名的新闻媒体&#xff0c;为公众提供准确、全面、及时的新闻报道和深度分析。我们致力于为全球读者带来约旦及地区的最新动态&#xff0c;涵盖政治、经济、社会…