一 准备阅读分支
到Github上Fork源码到自己的github(没有github账号先注册一个)。
然后选择一个发布tag,比如我选择v2.2.5.RELEASE的源码,再创建一个分支用于阅读源码和写注释。
二 源码模块结构分析
模块说明
| 模块 | 模块描述 |
|---|---|
| spring-cloud-gateway-core | 网关核心模块 |
| spring-cloud-gateway-dependencies | 网关依赖 |
| spring-cloud-gateway-mvc | MVC测试代码 |
| spring-cloud-gateway-sample | 网关使用示例 |
| spring-cloud-gateway-webflux | webflux |
| spring-cloud-starter-gateway | 网关Starter |
| docs | 网关文档 |
网关核心模块是网关的核心代码,对应包的说明如下:
通过命令
find . -name "*.java"|xargs cat|grep -v -e ^$ -e ^\s*\/\/.*$|wc -l查询每个包下的代码行数(去掉注释与空行之后的)
| 包路径 | 描述 | 行数 |
|---|---|---|
| org.springframework.cloud.gateway.actuate | 网关actuator监控端点 | 322 |
| org.springframework.cloud.gateway.config | 网关配置 | 2029 |
| org.springframework.cloud.gateway.discovery | 服务发现 | 412 |
| org.springframework.cloud.gateway.event | 网关定义的事件 | 186 |
| org.springframework.cloud.gateway.filter | 过滤器 | 7332 |
| org.springframework.cloud.gateway.handler | 谓词处理器 | 1900 |
| org.springframework.cloud.gateway.route | 路由 | 2386 |
| org.springframework.cloud.gateway.support | 其他支持 | 2372 |
| 总行数:16939 |
通过以上行数统计,我们主要阅读的核心代码行数仅一万多行。
我们只需要吃透这一万多行代码即可。
但是,非常重要的一点,阅读Spring Cloud Gateway源码之前一定要先了解Webflux,否则很多代码会看不懂,因为Webflux的编码风格与我们的webmvc的方式区别非常大。
另外,事先了解以下这张官网的图有利于我们阅读源码。

三 IDEA编译源码
编译环境:JDK 1.8、IDEA、apache-maven-3.6.3(官网建议不要低于3.3.3)
发现如下报错
1 | Cannot resolve plugin org.codehaus.mojo:flatten-maven-plugin:<unknown> |
官网的建议是要激活SpringMaven配置文件,以解析Spring里程碑和快照存储库.即如下:

但是不知具体是什么原因,可能与IDEA编译环境有关,我的IDEA还是报错,无法编译,故通过以下方式解决了报错问题,确保依赖没问题。
解决办法 在pom里分别找到这两个插件加上版本号:
1 | <groupId>org.jetbrains.kotlin</groupId> |
刷新依赖,依赖报错就不见了。
至此,直接运行spring-cloud-gateway-sample模块下的org.springframework.cloud.gateway.sample.GatewaySampleApplication的即可直接启动网关调试。
如果你们准备源码阅读环境遇到问题了,欢迎联系我,可以帮忙看看是什么原因构建不了。
