第一种方法:
systemctl服务自启动
在/usr/lib/systemd/system目录下,创建service:start_jar.servie
bash
[Unit]
Description=Your Java Application as a Service
After=network.target
[Service]
User=root
Type=simple
ExecStart=/usr/bin/java -jar /data/*.jar
Restart=on-failure
[Install]
WantedBy=multi-user.target
启动
bash
配置生效:systemctl daemon-reload
启动:systemctl start start_jar.service
启停止:systemctl stop start_jar.service
自启动:systemctl enable start_jar.service
第二种方法:
编写脚本auto_start.sh加载到rc.local启动服务中
如下:自动生成脚本:auto_create.sh
bash
#!/bin/bash
ScriptPath=/data/auto_start.sh
ScriptPathb=/data/auto_start_bak.sh
if [ -z "$1" ]; then
echo "jar包的路径不能为空!"
exit 1
fi
if [ -f "$ScriptPath" ]; then
echo "文件存在,需要删除!"
cp $ScriptPath $ScriptPathb
touch $ScriptPath
else
touch $ScriptPath
echo "空脚本创建成功"
echo "#!/bin/bash" >> $ScriptPath
echo "nohup java -jar $1 >/dev/null 2>&1 &" >> $ScriptPath
echo "脚本初始化成功"
chmod +x /data/auto_start.sh
#vim /etc/rc.local 打开添加在最后一行。/data/auto_start.sh
#备份:rc.local
cp /etc/rc.local /etc/rc.local_bak
#加载启动脚本到rc.local
echo "$ScriptPath" >> /etc/rc.local
chmod +x /etc/rc.local
echo "脚本添加到自启动中"
fi
执行脚本
bash
sh auto_create.sh jar包路径