当前位置: 首页 > news >正文

【源码】Spring Cloud Gateway 是在哪里匹配路由的?

我们知道,经过网关的业务请求会被路由到后端真实的业务服务上去,假如我们使用的是Spring Cloud Gateway,那么你知道Spring Cloud Gateway是在哪一步去匹配路由的吗?

源码之下无秘密,让我们一起从源码中寻找答案。

入口

Spring Cloud Gateway 的入口为 DispatcherHandlerhandle 方法,其中主要逻辑有获取Hander 和 执行Handler

获取Handler

获取 Handler 的时候,handlerMappings 中包含有一个 RoutePredicateHandlerMapping 实例,其获取 Handler 的实现最终会调用到 getHandlerInternal 方法。

org.springframework.cloud.gateway.handler.RoutePredicateHandlerMapping

getHandlerInternal 方法会调用了 lookupRoute 方法去获取路由。

其中:

  • 第一步是从缓存中获取路由列表,源码解析见:
  • 第二步是调用每个路由的断言去匹配当前请求,匹配到就直接返回,忽略后续所有其他路由。

获取到路由后将路由信息设置到 exchangegatewayRoute 属性上,然后返回 Handler

其中RoutePredicateHandlerMapping 实例是在 GatewayAutoConfiguration 中配置好的。

org.springframework.cloud.gateway.config.GatewayAutoConfiguration

public class GatewayAutoConfiguration {// ...@Beanpublic RouteLocator routeDefinitionRouteLocator(GatewayProperties properties,List<GatewayFilterFactory> gatewayFilters,List<RoutePredicateFactory> predicates,RouteDefinitionLocator routeDefinitionLocator,ConfigurationService configurationService) {return new RouteDefinitionRouteLocator(routeDefinitionLocator, predicates,gatewayFilters, properties, configurationService);}@Bean@Primary@ConditionalOnMissingBean(name = "cachedCompositeRouteLocator")// TODO: property to disable composite?public RouteLocator cachedCompositeRouteLocator(List<RouteLocator> routeLocators) {return new CachingRouteLocator(new CompositeRouteLocator(Flux.fromIterable(routeLocators)));}@Beanpublic RoutePredicateHandlerMapping routePredicateHandlerMapping(FilteringWebHandler webHandler, RouteLocator routeLocator,GlobalCorsProperties globalCorsProperties, Environment environment) {return new RoutePredicateHandlerMapping(webHandler, routeLocator,globalCorsProperties, environment);}// ...
}}

结论

综上,Spring Cloud Gateway 的路由匹配是在获取 Handler 的过程中,在 RoutePredicateHandlerMapping 中实现的,具体实现方法为 lookupRoute。最后将匹配到的路由设置到 exchangegatewayRoute 属性上,供后续获取并使用。

http://www.lryc.cn/news/60438.html

相关文章:

  • BAT批处理基本命令
  • Python数组仿射变换
  • “==“和equals方法究竟有什么区别?
  • 蓝桥杯15单片机--超声波模块
  • 【学习笔记】ARC159
  • 2023/4/16总结
  • 【剑指offer】常用的数据增强的方法
  • /lib/lsb/init-functions文件解析
  • 【ChatGPT】ChatGPT-5 强到什么地步?
  • [ARM+Linux] 基于全志h616外设开发笔记
  • 如何实现24小时客户服务
  • 查询数据库空间(mysql和oracle)
  • 为什么 SQLite 一定要用 C 语言来开发?
  • TensorFlow Lite,ML Kit 和 Flutter 移动深度学习:6~11
  • 你的GPT跟ChatGPT可能只差了一个DPU
  • springboot服务端接口外网远程调试,并实现HTTP服务监听 - 内网穿透
  • NumPy的应用-1
  • k8s的yaml文件中kind类型详解
  • 第三天:C语言控制结构
  • 访问若依vue版后端api接口
  • 另一种迁移xxl-job任务的方法,适合不满足数据迁移条件
  • Redis缓存穿透、击穿、雪崩面试题详解
  • 【网络安全】本地提权漏洞分析
  • 电脑端(PC)按键精灵——3.其他命令
  • Hudi集成Flink-写入方式
  • 深度探索list
  • QQuick-自绘
  • 【算法】【算法杂谈】已知[1,m]的等概率函数,求[1,n]的等概率函数
  • 【Python】Python中的列表,元组,字典
  • 分布式系统概念和设计-分布式对象和远程调用