前不久华为云崩溃了,恢复以后还要登录服务器手动把项目跑起来,emmm,万一项目多几个那不就尴尬了。作为优秀劳动生产能手的我,当然还要了解一下自动化运维啊。那么试试让项目跟随服务器启动自启吧。实验所用的是 CentOS8 ,自启方面跟测试服务器的 CentOS7 差别不大
首先,写一个最简单的 Springboot 应用,里面放一个 web 页面。项目结构大概就这样,懂的都懂。因为是测试的,所以这是很简单了
写完打包成jar,上传 CentOS8 。我放在 /home 路径下,命名为 ifrs17-service.jar
安装 JDK 这种就不废话了,接下来先写一个手动启动的脚本 autodeploy.sh
----------------------------------------------------------------------------------------------------------------------------------------------
#!/bin/bash
echo "-------source /etc/profile--------------------------------" >> /usr/local/ifrs17/azure/server/1.txt
source /etc/profile
echo "-------export JDK--------------------------------" >> /usr/local/ifrs17/azure/server/1.txt
export JAVA_HOME=/usr/local/jdk1.8.0_172
export PATH=${JAVA_HOME}/bin:$PATH
echo "-------ifrs17 system service starting--------------------------------" >> /usr/local/ifrs17/azure/server/1.txt
APP_NAME="ifrs17-service.jar"
usage() {
echo "case: sh autodeploy.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 "/usr/local/ifrs17/azure/server/${APP_NAME}" > /usr/local/ifrs17/azure/server/console.log 2>&1 &
echo $! > /usr/local/ifrs17/azure/server/pid.log
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=ifrs17 system service auto start
After=syslog.target network.target nss-lookup.target
[Service]
User=root
Type=forking
ExecStart=/bin/sh /usr/local/ifrs17/azure/server/autodeploy.sh start
ExecReload=/bin/sh /usr/local/ifrs17/azure/server/autodeploy.sh restart
ExecStop=/bin/sh /usr/local/ifrs17/azure/server/autodeploy.sh stop
[Install]
WantedBy=multi-user.targe
----------------------------------------------------------------------------------------------------------------------------------------------
这里不要用 ./home/autodeploy.sh start ,亲测报错…
写完保存,执行
systemctl enable autodeploy.service
发现系统将创建一个软连接到 /etc/systemd/system/multi-user.target.wants
此时重启就可以完成自启了