前不久华为云崩溃了,恢复以后还要登录服务器手动把项目跑起来,emmm,万一项目多几个那不就尴尬了。作为优秀劳动生产能手的我,当然还要了解一下自动化运维啊。那么试试让项目跟随服务器启动自启吧。实验所用的是 CentOS8 ,自启方面跟测试服务器的 CentOS7 差别不大
首先,写一个最简单的 Springboot 应用,里面放一个 web 页面。项目结构大概就这样,懂的都懂。因为是测试的,所以这是很简单了
写完打包成jar,上传 CentOS8 。我放在 /home 路径下,命名为 auto-start-0.0.1-SNAPSHOT.jar
安装 JDK 这种就不废话了,接下来先写一个手动启动的脚本 autodeploy.sh
#!/bin/bash
export JAVA_HOME=/usr/java/jdk1.8.0_241-amd64
export PATH=${JAVA_HOME}/bin:${PATH}
APP_NAME="auto-start-0.0.1-SNAPSHOT.jar"
usage() {
echo "case: sh run.sh [start|stop|restart|status]"
exit 1
}
isExist(){
#grep -v grep 反向选取记录行,此处为选取不带grep内容的结果
#awk 选取列
pid=`ps -ef | grep ${APP_NAME} | grep -v grep | awk '{print $2}'`
#如果不存在返回1,存在返回0
if [ -z "${pid}" ]; then
return 1
else
return 0
fi
}
start(){
isExist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is already running,pid = ${pid}."
else
nohup java -jar "/home/${APP_NAME}" > /dev/null 2>&1 &
echo "${APP_NAME} start success"
fi
}
stop(){
isExist
if [ $? -eq "0" ]; then
kill -9 ${pid}
else
echo "${APP_NAME} is not running"
fi
}
status(){
isExist
if [ $? -eq "0" ]; then
echo "${APP_NAME} is running. Pid is ${pid}"
else
echo "${APP_NAME} is not running"
fi
}
restart(){
stop
start
}
case "$1" in
"start")
start
;;
"stop")
stop
;;
"status")
status
;;
"restart")
restart
;;
*)
usage
;;
esac
通过脚本也可以手动启动项目,脚本会自检项目是否启动,并输出对应的信息
脚本写完,就是自启的重头戏,在 /etc/systemd/system 创建 autodeploy.service
[Unit]
Description=Springboot project for test auto start
After=syslog.target network.target nss-lookup.target
[Service]
User=root
Type=forking
# ExecStart=nohup java -jar /home/auto-start-0.0.1-SNAPSHOT.jar &
ExecStart=sh /home/autodeploy.sh start
ExecReload=sh /home/autodeploy.sh restart
ExecStop=sh /home/autodeploy.sh stop
[Install]
WantedBy=multi-user.target
这里不要用 ./home/autodeploy.sh start ,亲测报错…
写完保存,执行
systemctl enable autodeploy.service
发现系统将创建一个软连接到 /etc/systemd/system/multi-user.target.wants
此时重启就可以完成自启了
至于在 ExecStart 直接写命令还是通过脚本启动,这件事,我觉得还是仁者见仁智者见智吧