如何使用GitHub Actions实现Spring Boot程序的持续部署(CD)
由于学习上的需要,我需要不断对GitHub上的分支进行合并与持续向远端推送。虽然手动操作并不难,但次数较多时,自动化部署功能显得尤为必要。本文将介绍如何利用GitHub Actions实现Spring Boot程序的持续部署。
Actions基本使用方法
基本概念
- workflow:GitHub的配置文件,存放在
.github/workflow
文件夹中。
- job:一个workflow由多个job构成。
- step:每个job分为多个步骤。
- action:每个步骤执行的具体动作。
字段解释
runs-on
选择执行环境,目前支持的环境包括:
ubuntu-latest
windows-latest
macos-latest
uses
调用GitHub市场中的预定义脚本。例如:
uses: actions/checkout@v4
|
使用Actions将Java程序部署到远程服务器上
使用Maven打包
- 进入GitHub Actions管理界面,创建新workflow。
- 选择Java with Maven模板,配置以下内容:
name: Java CI with Maven on: push: branches: ["main"] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up JDK 8 uses: actions/setup-java@v4 with: java-version: '8' distribution: 'temurin' cache: maven - name: Build with Maven run: mvn -B clean package --file ./Blog-api/pom.xml
|
远程推送Java包到远程服务器
使用easingthemes/ssh-deploy
插件:
- name: deploy uses: easingthemes/ssh-deploy@v2.1.1 env: SSH_PRIVATE_KEY: ${{ secrets.ACCESS_TOKEN }} ARGS: "-avzr --delete" SOURCE: "Blog-api/target/Blog-api-0.0.1-SNAPSHOT.jar" REMOTE_HOST: ${{ secrets.REMOTE_HOST }} REMOTE_USER: ${{ secrets.REMOTE_USER }} TARGET: ${{ secrets.TARGET }}
|
在远程服务器上部署
使用appleboy/ssh-action
插件执行命令:
- name: deploy1 uses: appleboy/ssh-action@v1.0.3 with: host: ${{ secrets.REMOTE_HOST }} username: ${{ secrets.REMOTE_USER }} key: ${{ secrets.ACCESS_TOKEN }} script: | /home/traveller/config/replayjar
|
最终呈现
完整的workflow配置文件如下:
name: Java CI with Maven on: push: branches: ["main"] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Set up JDK 8 uses: actions/setup-java@v4 with: java-version: '8' distribution: 'temurin' cache: maven - name: Build with Maven run: mvn -B clean package --file ./Blog-api/pom.xml - name: deploy uses: easingthemes/ssh-deploy@v2.1.1 env: SSH_PRIVATE_KEY: ${{ secrets.ACCESS_TOKEN }} ARGS: "-avzr --delete" SOURCE: "Blog-api/target/Blog-api-0.0.1-SNAPSHOT.jar" REMOTE_HOST: ${{ secrets.REMOTE_HOST }} REMOTE_USER: ${{ secrets.REMOTE_USER }} TARGET: ${{ secrets.TARGET }} - name: deploy1 uses: appleboy/ssh-action@v1.0.3 with: host: ${{ secrets.REMOTE_HOST }} username: ${{ secrets.REMOTE_USER }} key: ${{ secrets.ACCESS_TOKEN }} script: | /home/traveller/config/replayjar
|