前面学了作业关键字,但都是用echo测试效果,这次构建一个实际项目。并学三个作业关键字image、chache、artifacts
1、代码准备
在极狐gitlab上新建项目——从模板创建——使用spring模板——起个项目名称spring-item-demo
2、准备runner
saas版的极狐gitlab提供了共享runner,但每次构建会使用不同的runner。本地的runner配置方法点击这里 和这里
通过tag指定让当前项目使用本地的runner
我的runner使用了docker和jh这两个标签,在ci文件中指定即可
tags:
- jh
3、配置运行流水线
基本的流水线文件,提交后即可开始构建。构建的过程为:
①流水线根据tags关键字找到符合条件的runner
②runner内拉取maven:3.5.3镜像
③在maven镜像内执行mvn和ls这些指令
image: maven:3.5.3 #流水线在这个镜像内运行
stages:
- build
spring_build:
tags: #指定runner
- jh
stage: build
script:
- mvn clean install -Dmaven.test.skip=true
- ls target #查看构建好的jar包
4、加速
上一步的流水线理论上能实现构建,但是很慢甚至运行失败
1–mvn使用国内依赖
上图可以看出下载地址都在国外,所以很慢,这里参考了这篇文章使用国内地址
script:
- echo '<settings xmlns="http://maven.apache.org/SETTINGS/1.2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 https://maven.apache.org/xsd/settings-1.2.0.xsd">
<localRepository>/cache/.m2</localRepository>
<mirrors>
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
</mirrors>
</settings>' > $HOME/.m2/settings.xml
- mvn clean install -Dmaven.test.skip=true
2–使用cache关键字缓存
每次运行流水线都下一遍依赖非常浪费时间,把它缓存起来,第一次下载过后,后面就不用再从头下载
spring项目下载的依赖在.m2目录内
cache:
paths:
- .m2/
5、作业关键字artifacts下载产物
构建成功后只是能ls看到文件,想要拿到文件需要配置artifacts关键字。示例场景:发版的时候下载需要下载包
将上图的jar文件做成产物
artifacts:
paths:
- ./target/demo-0.0.1-SNAPSHOT.jar
流水线执行成功后可下载产物
下载解压后在jdk环境即可运行
java -jar demo-0.0.1-SNAPSHOT.jar
浏览器访问本机8080端口
测试成功。
这个示例的完整ci文件
image: maven:3.5.3 #流水线在这个镜像内运行
cache: #缓存依赖文件
paths:
- .m2/
stages:
- build
spring_build:
tags: #指定runner
- jh
stage: build
script:
- echo '<settings xmlns="http://maven.apache.org/SETTINGS/1.2.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 https://maven.apache.org/xsd/settings-1.2.0.xsd">
<localRepository>/cache/.m2</localRepository>
<mirrors>
<mirror>
<id>nexus-aliyun</id>
<mirrorOf>*</mirrorOf>
<name>Nexus aliyun</name>
<url>http://maven.aliyun.com/nexus/content/groups/public</url>
</mirror>
</mirrors>
</settings>' > $HOME/.m2/settings.xml
- mvn clean install -Dmaven.test.skip=true
- ls target #查看构建好的jar包
artifacts:
paths:
- ./target/demo-0.0.1-SNAPSHOT.jar
参考:
https://docs.gitlab.cn/jh/ci/yaml/#variables
https://www.bilibili.com/video/BV18y4y1S7VC?share_source=copy_web&vd_source=e7cb77928d906ea4d27387974d073399
http://t.csdn.cn/SrEjp