记一次基于 PowerShell 的 Git 自动化部署 Java 多服务实践

前言

有这么一个自动化部署的需求,凑巧 git 还直接建立在测试服务器上,部署后可以直接在测试服务器上演示

步骤

建立 Git 仓库

与一般的 Git 部署一样,区别是需要添加 --bare 开关,这样可以建立一个裸库(只有 .git 文件夹内容无工作区)而不是一个完整的库。

mkdir test.git
cd test.git
git init --bare

此时可以将本地代码推送到该库中,推送完成后还需要建立一个部署专用的工作区,这里放在 deploy 文件夹中。

mkdir deploy
cd deploy
# clone 可以使用 file:/// 地址也可以使用绝对或相对路径
git clone ../source/test
cd test
git fetch
git checkout master

编写自动部署脚本

要在 Git 仓库中建立一个自动化部署脚本,这里用 PowerShell 脚本,因为其面向对象简单好用

# 获取父文件夹名
$directoryName = (Get-ChildItem)[0].Parent.Name;
# 获取时间
$time = [datetime]::Now.ToString("yyyyMMddHHmmss");
# 输出地址
$logFilePath = "../log/$directoryName-$time.log"
# 操作用户名
$userName = whoami
"正在使用$userName账户部署$directoryName" > $logFilePath
# git 更新
git fetch --all *>> $logFilePath
git checkout origin/master *>> $logFilePath
git reset --hard *>> $logFilePath
# maven 编译
bash mvnw clean *>> $logFilePath
bash mvnw compile *>> $logFilePath
bash mvnw package *>> $logFilePath
# 执行 jar 包,这里使用 Screen 运行
$jars=dir -r *.jar
$jars=$jars | where {$_.Parent.Name -match "target"}
$jars | foreach {
    screen -S "$($_.BaseName)-master" -X stuff "^C";
    screen -XS "$($_.BaseName)-master" quit;
    screen -wipe;
    screen -dmS "$($_.BaseName)-master";
    screen -S "$($_.BaseName)-master" -X stuff "java -Dfile.encoding=utf8 -jar $($_.FullName)`n"
}
# 编译前端
cd ui
$logFilePath = "../" + $logFilePath
npm install *>> $logFilePath
npm run build:prod *>> $logFilePath
# 部署前端
rm -rf /wwwroot
mv dist /wwwroot
chmod -R 755 /wwwroot
chown -R nginx:nginx /wwwroot
service nginx restart *>> $logFilePath
"部署完成" *>> $logFilePath

添加 Git Hook 自动化脚本

在上一步新建的库中可以看到 hooks 文件夹,hooks 文件夹就是放置 Git 各种事件触发后执行的命令的地方,新建一个 post-receive 文件,并赋予权限 777,并写入下面的代码:

#!/usr/bin/bash
# 判断是否为远程仓库
IS_BARE=$(git rev-parse --is-bare-repository)
if [ -z "$IS_BARE" ]; then
echo >&2 "fatal: post-receive: IS_NOT_BARE $IS_BARE"
exit 1
fi
echo "正在进行自动部署"
unset GIT_DIR
# 部署路径
DeployPath="/root/deploy/test"
cd $DeployPath
# 执行部署脚本
pwsh ./Start-Deploy.ps1
echo "部署已完成"

至此再次提交新代码时可以自动化部署到前端了

参考

Git 服务器 利用 hook 实现自动部署

posted @ 2022-06-09 14:20  Aoba_xu  阅读(121)  评论(0编辑  收藏  举报