Linux通过脚本设置开机自启jar包

timo-nbktp 1年前 ⋅ 1247 阅读

1、创建工作目录

创建jar部署的目录,并且将jar上传到该目录下

mkdir -p /home/java-server/test-demo

2、创建启动脚本

进入jar目录:

cd  /home/java-server/test-demo

创建脚本文件:

vim start.sh

启动脚本内容:

#!/bin/sh
export LANG="en_US.UTF-8"
cd /home/java-server/test-demo
runMessage=`ps aux | grep \`cat pidfile.txt\``
projectStartCommand="/usr/local/java/jdk1.8.0_131/bin/java -jar xxx.jar"
if [[ $runMessage == *$projectStartCommand* ]]
then
    echo "Application has starting ,restarting..."
    kill -9 `cat pidfile.txt`
    nohup /usr/local/java/jdk1.8.0_131/bin/java -jar xxx.jar -java.tmp.dir=/home/java-server/test-demo/temp >/dev/null 2>&1 & echo $! > pidfile.txt
else
    echo "Application has stopped ,starting..."
    nohup /usr/local/java/jdk1.8.0_131/bin/java -jar xxx.jar -java.tmp.dir=/home/java-server/test-demo/temp >/dev/null 2>&1 & echo $! > pidfile.txt
fi
  • 脚本中/home/java-server/test-demo就是jar包所在的,可以根据实际情况定。
  • xxx.jar为实际的jar包名称。
  • /usr/local/java/jdk1.8.0_131/bin/java为jdk环境所在路径。

3、创建停止脚本

进入jar目录:

cd  /home/java-server/test-demo

创建脚本文件:

vim stop.sh

停止脚本内容:

#!/bin/sh
cd /home/java-server/test-demo
PID=$(cat pidfile.txt)
if [ ${PID} ]; 
then
    echo 'Application is stpping...'
    echo kill $PID DONE
    kill $PID
else
    echo 'Application is already stopped...'
fi

4、设置开机自启

进入system:

# 进入system
cd /usr/lib/systemd/system/ 

创建自启脚本:

vim xxx.service

xxx.service为脚本的名称,一般来就是jar包前缀名称一致,比如:test-demo.service

内容如下:

[Unit]
Description=xxx
After=network.target

[Service]
Type=forking
ExecStart=/home/java-server/test-demo/start.sh
ExecStop=/home/java-server/test-demo/stop.sh
PrivateTmp=true

[Install]
WantedBy=multi-user.target
  • Description:描述,一般为项目名称
  • ExecStart:开启脚本位置
  • ExecStop:停止脚本位置

设置脚本权限:

# 自启文件
chmod 777 xxx.service
# 启动文件
chmod 777  /home/java-server/test-demo/start.sh
# 停止文件
chmod 777  /home/java-server/test-demo/stop.sh

加入自启命令 :

systemctl daemon-reload
systemctl enable xxx.service

启动|停止命令:

# 启动
systemctl start xxx

# 停止
systemctl stop xxx

 

xxx就是xxx.service的前缀。

 

--end--

 

 

版权 本着开源共享、共同学习的精神,本文转载自 https://blog.csdn.net/zhuocailing3390/article/details/123007090 , 如果侵权之处,请联系博主进行删除,谢谢~