gitlab ci提速核心是优化任务调度而非堆硬件,关键靠parallel拆分、needs精准依赖、缓存与artifacts协同。parallel支持基础并行与矩阵式组合;needs打破stage串行,实现跨阶段依赖;artifacts显式传递产物,配合runner并发配置确保实效。

GitLab CI 提升速度的核心不是加机器,而是让任务真正“该并行的并行、该等待的才等待”。关键配置就三点:用 parallel 拆任务、用 needs 控制作业依赖、配合缓存减少重复开销。
parallel:把一个任务拆成多份同时跑
适合可分割、彼此独立的作业,比如测试、构建、扫描。GitLab 会自动分配子任务,并通过 $CI_NODE_INDEX 区分上下文。
- 基础写法(4 个并行实例):
test: stage: test script: ./run_tests.sh parallel: 4
- 矩阵式并行(多环境组合):
e2e-test: stage: test script: npm run e2e -- --browser=$BROWSER parallel: matrix: - BROWSER: [chrome, firefox] OS: [ubuntu-latest, macos-latest]
needs:打破 stage 顺序,只等真正需要的上游作业
默认按 stage 串行(build → test → deploy),但实际很多部署只需 build 结果,不必卡在 test 后面。needs 让你精准指定依赖:
-
deploy-dev和deploy-staging可同时启动,只要都等build完成:deploy-dev: stage: deploy script: ./deploy.sh dev needs: [build] deploy-staging: stage: deploy script: ./deploy.sh staging needs: [build]
-
多依赖合并触发(如发布前必须单元测试 + 集成测试都通过):
release: stage: deploy script: ./publish.sh needs: [unit_test, integration_test]
缓存 + artifacts:避免重复劳动,确保产物可靠传递
并行任务之间不共享文件系统,靠 artifacts + needs 显式传递产物,比全局 cache 更安全可控:
- 构建作业生成 jar 并声明产物:
build: stage: build script: mvn package -DskipTests artifacts: paths: [target/*.jar] - 测试作业明确依赖 build,才能拿到最新 jar:
test: stage: test script: mvn test needs: [build] # 必须写,否则可能读到旧缓存或空目录
Runner 资源要跟上
光配 parallel: 4 没用,还得确保 Runner 能并发执行:
- 编辑
config.toml,调高concurrent(比如设为 8):concurrent = 8
- Docker Executor 下注意挂载持久化路径(如
/cache),避免容器重启丢缓存。
不复杂但容易忽略











