如果沒有使用敏捷部署方式咒吐,每次服務(wù)器開機(jī)關(guān)機(jī)待逞,都要通過 nohup java -jar hello.jar > /dev/null & 命令進(jìn)行服務(wù)的啟動酪耕,未免太過于繁瑣呜象,通過自定義服務(wù)的方式, 省去不少麻煩晚岭。
- 先上 jar包的啟動腳本,
#!/bin/bash
JAVA_HOME=/usr/local/app/jdk1.8.0_191
PATH=$PATH:$JAVA_HOME/bin # shell腳本必須指定鸥印,因為腳本不會自動加載環(huán)境變量,不寫的話導(dǎo)致出現(xiàn)此錯誤
app='/usr/local/hello/hello.jar' #jar包的決定路徑
args='-server -Xms1024m -Xmx1024m -XX:PermSize=128m -XX:SurvivorRatio=2 -XX:+UseParallelGC' #java程序啟動參數(shù)坦报,可不寫
LOGS_FILE=/dev/null # 把打印的日志扔進(jìn)垃圾桶
cmd=$1 #獲取執(zhí)行腳本的時候帶的參數(shù)
pid=`ps -ef|grep java|grep $app|awk '{print $2}'` # 抓取對應(yīng)的java進(jìn)程
startup(){
aa=`nohup java -jar $args $app >> $LOGS_FILE 2>&1 &`
echo $aa
}
if [ ! $cmd ]; then
echo "Please specify args 'start|restart|stop'"
exit
fi
if [ $cmd == 'start' ]; then
if [ ! $pid ]; then
startup
else
echo "$app is running! pid=$pid"
fi
fi
if [ $cmd == 'restart' ]; then
if [ $pid ]
then
echo "$pid will be killed after 3 seconds!"
sleep 3
kill -9 $pid
fi
startup
fi
if [ $cmd == 'stop' ]; then
if [ $pid ]; then
echo "$pid will be killed after 3 seconds!"
sleep 3
kill -9 $pid
fi
echo "$app is stopped"
fi
寫好腳本之后库说,需要為腳本添加可執(zhí)行權(quán)限
chmod +x hello-service.sh
- 自定義開機(jī)啟動命令
2.1 進(jìn)入到/etc/systemd/system/
# vi hello-service.service
[Unit]
Description=hello-service
after=network.target
[Service]
User=root
Group=root
Type=forking
KillMode=process
ExecStart=/bin/sh /usr/local/hello/hello-service.sh start
ExecReload=/bin/sh /usr/local/hello/hello-service.sh restart
ExecStop=/bin/sh /usr/local/hello/hello-service.sh stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
2.2 添加執(zhí)行權(quán)限
chmod +x hello-service.service
2.3 添加開機(jī)啟動服務(wù)
systemctl enable hello-service.service #添加開機(jī)啟動服務(wù)
systemctl start hello-service.service # 啟動服務(wù)
systemctl stop hello-service.service #關(guān)閉服務(wù)
systemctl restart hello-service.service # 重啟服務(wù)
systemctl status hello-service.service #查看服務(wù)狀態(tài)
systemctl disable hello-service.service #取消開機(jī)啟動