CI/CD流水线实战
CI/CD流水线实战
CI/CD(持续集成/持续交付)是现代软件开发的核心实践,通过自动化流程保障代码质量和交付效率。
CI/CD核心流程
代码提交 → 自动构建 → 单元测试 → 代码扫描 → 集成测试 → 制品构建 → 部署预发 → 生产发布
Maven自动化构建
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.10</version>
<executions>
<execution>
<goals><goal>prepare-agent</goal></goals>
</execution>
<execution>
<id>report</id>
<phase>test</phase>
<goals><goal>report</goal></goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
GitLab CI示例
# .gitlab-ci.yml
stages:
- build
- test
- quality
- package
- deploy
variables:
MAVEN_OPTS: "-Dmaven.repo.local=.m2/repository"
cache:
key: ${CI_COMMIT_REF_SLUG}
paths:
- .m2/repository
build:
stage: build
script:
- mvn compile -B
only:
- merge_requests
- main
unit-test:
stage: test
script:
- mvn test -B
coverage: '/Code coverage: \d+\.\d+/'
artifacts:
reports:
junit:
- target/surefire-reports/TEST-*.xml
sonar-check:
stage: quality
script:
- mvn sonar:sonar -Dsonar.qualitygate.wait=true
package:
stage: package
script:
- mvn package -DskipTests -B
artifacts:
paths:
- target/*.jar
deploy-staging:
stage: deploy
script:
- kubectl set image deployment/app app=registry.example.com/app:$CI_COMMIT_SHA
environment:
name: staging
only:
- main
流水线阶段设计
并行测试
test-unit:
stage: test
script: mvn test -B -Dtest=UnitTests
test-integration:
stage: test
script: mvn test -B -Dtest=IntegrationTests
services:
- name: mysql:8.0
alias: test-db
variables:
DB_HOST: test-db
制品版本管理
#!/bin/bash
# 版本号策略:语义化版本 + Git SHA
VERSION=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)
GIT_SHA=$(git rev-parse --short HEAD)
docker build -t registry.example.com/app:${VERSION}-${GIT_SHA} .
小结
CI/CD自动化流程是团队协作和快速交付的基石,合理的流水线设计能显著提升研发效能。