GitLab CI优化:仅传递WAR文件以降低部署阶段开销
问题1:缓存拉取开销优化
既然已经固定使用同一Runner,可通过两个调整降低缓存开销:
- 缩小缓存范围:只缓存
.m2/repository(Maven依赖,是跨阶段真正需要复用的内容)和target下的WAR文件,而非整个target目录; - 调整缓存策略:仅在build阶段执行
pull-push,其他阶段只用pull,避免重复推送缓存到Minio。
问题2:仅获取WAR文件到部署阶段
核心是让nexus阶段只产出WAR文件作为制品,后续部署阶段依赖时只会下载该文件,无需整个target:
- 修改nexus阶段的
artifacts.paths,明确指定只包含target/*.war; - 部署阶段(deploy-test/deploy-prod)无需产出制品,可直接去掉自身的
artifacts配置。
修改后的完整.gitlab-ci.yml示例
cache: key: ${CI_COMMIT_REF_SLUG} paths: - .m2/repository/ - target/*.war policy: pull-push stages: - build - nexus - deploy-test - deploy-prod build: stage: build script: - 'mvn $MAVEN_CLI_OPTS clean -U compile -T 6 process-classes -DjspcGoal=compile' artifacts: expire_in: 3 days paths: - target/classes/ # 仅传递编译后的类文件给nexus阶段,减少冗余 nexus: stage: nexus script: - 'mvn $MAVEN_CLI_OPTS -DskipTests deploy' artifacts: expire_in: 3 days paths: - target/*.war # 仅产出WAR文件作为制品 dependencies: - build needs: - job: build artifacts: true deploy-test: stage: deploy-test script: - 'mvn $MAVEN_CLI_OPTS -DskipTests cargo:redeploy -Dcontext=${contextAndVersion} -Dtarget=staging.www' dependencies: - nexus needs: - job: nexus artifacts: true cache: policy: pull # 仅拉取缓存,不推送 deploy-prod: stage: deploy-prod script: - 'mvn $MAVEN_CLI_OPTS -DskipTests cargo:redeploy -Dcontext=${contextAndVersion} -Dtarget=prod.www' dependencies: - nexus needs: - job: nexus artifacts: true cache: policy: pull # 仅拉取缓存,不推送
额外说明
- build阶段的artifacts只传
target/classes,是因为nexus阶段执行deploy仅需要编译后的类文件打包成WAR,比传递整个target更轻量化; - 若部署阶段的Maven命令不需要本地依赖,可直接在部署阶段添加
cache: {}完全禁用缓存,进一步减少开销。
内容的提问来源于stack exchange,提问作者Fred
相关产品推荐
相关产品推荐

