背景
系统发布使用 新的 devops平台,使用maven构建的速度特别缓慢,一个api,service两个moudle 打包上传需要5-7分钟。
现状
使用maven命令打包部署
maven clean package depoly -U -Dmaven.test.skip=true -e
为啥这么慢?maven在做啥
查看maven 的日志,maven 每次都会重新下载SNAPSHOT包,而且多次出现recompiling。
可以添加 -X参数,打印debug日志。
maven 编译,打包的几个关键参数
使用 mvn --help 查看maven构建的参数
-U
强制检查丢失的releases版本和更新远程的snapshots版本
-U,--update-snapshots Forces a check for missing
releases and updated snapshots on
remote repositories
-T
线程数量,2C是代表当前核数*2
-T,--threads <arg> Thread count, for instance 2.0C
where C is core multiplied
-pl
只构建需要的项目,父类项目不构建
-pl,--projects <arg> Comma-delimited list of specified
reactor projects to build instead
of all projects. A project can be
specified by [groupId]:artifactId
or by its relative path
插件配置
maven 定义了生命周期,插件才是真正干活的。
跳过测试
//命令行参数
-Dmaven.skip.test=true
增量构建
查看编译日志时发现多次出现如下日志:
2024-08-21 10:18:39[INFO] Changes detected - recompiling the module!(检测到更改——正在重新编译模块!)
这是增量构建导致的。
如何关闭增量构建
//命令行参数
-Dmaven.compiler.useIncrementalCompilation=false
// 插件配置
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<useIncrementalCompilation>false</useIncrementalCompilation>
</configuration>
</plugin>
</plugins>
</build>
to enable/disable incremental compilation feature.
This leads to two different modes depending on the underlying compiler. The default javac compiler does the following:
- true (default) in this mode the compiler plugin determines whether any JAR files the current module depends on have changed in the current build run; or any source file was added, removed or changed since the last compilation. If this is the case, the compiler plugin recompiles all sources.
- false (not recommended) this only compiles source files which are newer than their corresponding class files, namely which have changed since the last compilation. This does not recompile other classes which use the changed class, potentially leaving them with references to methods that no longer exist, leading to errors at runtime.
“启用 / 禁用增量编译功能。这会根据底层编译器产生两种不同的模式。默认的 javac 编译器会进行以下操作:
true(默认值):在这种模式下,编译器插件会确定当前模块所依赖的任何 JAR 文件在当前构建运行中是否发生了变化;或者自上次编译以来是否有任何源文件被添加、删除或更改。如果是这种情况,编译器插件会重新编译所有源文件。
false(不推荐):这种模式下只会编译比其对应的类文件更新的源文件,即自上次编译以来发生了变化的源文件。这不会重新编译使用了已更改类的其他类,可能会导致这些类中保留对不再存在的方法的引用,从而在运行时产生错误。”
总结
- api被其他项目依赖,service不被其他项目依赖。添加-pl参数
- 删除-U命令
- 关闭增量构建 。添加 -Dmaven.compiler.useIncrementalCompilation=false
现在统一取消-U命令,并且关闭增量构建
mvn clean package install deploy -T4C -Dmaven.test.skip=true -Dmaven.compiler.useIncrementalCompilation=false -pl api
mvn clean package -T4C -Dmaven.test.skip=true -Dmaven.compiler.useIncrementalCompilation=false -pl service
构建现在只需要2分钟
观察日志,阅读文档,调整参数。