Skip to content

GitLab CI 集成

.gitlab-ci.yml 配置

yaml
# .gitlab-ci.yml

variables:
  GRADLE_OPTS: "-Dorg.gradle.daemon=false"
  GRADLE_USER_HOME: "$CI_PROJECT_DIR/.gradle"

# 缓存 Gradle 依赖(加速构建)
cache:
  key: "$CI_COMMIT_REF_SLUG"
  paths:
    - .gradle/wrapper
    - .gradle/caches

stages:
  - build
  - test
  - quality
  - deploy

before_script:
  - chmod +x gradlew

build:
  stage: build
  image: eclipse-temurin:17-jdk
  script:
    - ./gradlew assemble --build-cache --parallel
  artifacts:
    paths:
      - build/libs/*.jar
    expire_in: 1 hour

test:
  stage: test
  image: eclipse-temurin:17-jdk
  script:
    - ./gradlew test --build-cache
  artifacts:
    when: always
    reports:
      junit: '**/build/test-results/test/*.xml'
    paths:
      - build/reports/tests/

code-quality:
  stage: quality
  image: eclipse-temurin:17-jdk
  script:
    - ./gradlew checkstyleMain jacocoTestReport
  artifacts:
    reports:
      coverage_report:
        coverage_format: jacoco
        path: build/reports/jacoco/test/jacocoTestReport.xml
    paths:
      - build/reports/

deploy-staging:
  stage: deploy
  script:
    - ./gradlew bootJar
    - scp build/libs/*.jar user@staging.example.com:/app/
  only:
    - develop

deploy-production:
  stage: deploy
  script:
    - ./gradlew publish
  only:
    - main
  when: manual  # 手动触发

使用 Docker 服务(集成测试)

yaml
integration-test:
  stage: test
  image: eclipse-temurin:17-jdk
  services:
    - mysql:8.0
    - redis:7.0
  variables:
    MYSQL_ROOT_PASSWORD: testpassword
    MYSQL_DATABASE: testdb
    SPRING_DATASOURCE_URL: jdbc:mysql://mysql/testdb
    SPRING_REDIS_HOST: redis
  script:
    - ./gradlew integrationTest

下一步