设置Java服务开机自启动
方法一:
新建Jar包运行脚本my_project.sh
,路径根据实际情况修改:
#!/bin/bash
nohup java -jar /root/my_project/my_project-1.0.0.jar --spring.config.location=/root/my_project/application-dev.yml >> /root/my_project/log.out 2>&1 &
修改/etc/rc.local
文件,文件末尾添加/root/my_project/my_project.sh &
:
#!/bin/bash
# THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES
#
# It is highly advisable to create own systemd services or udev rules
# to run scripts during boot instead of using this file.
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.
touch /var/lock/subsys/local
/root/my_project/my_project.sh &
将chsm-host.sh
、rc.local
设为可执行文件:
chmod +x /root/my_project/my_project.sh
chmod +x /etc/rc.d/rc.local
重启服务器查看Java服务是否重启
🏆方法二:
一、编写jar启动执行的脚本
vim new_monitor-start.sh
脚本:
#!/bin/sh
nohup /usr/local/java/jdk1.8.0_171/bin/java -jar /home/new_monitor/jar/monitor/new_monitor.jar > /home/new_monitor/jar/monitor/new_monitor.log &
echo $! > /var/run/new_monitor.pid
二、编写jar停止执行的脚本
vim new_monitor-stop.sh
#!/bin/bash
PID=$(cat /var/run/new_monitor.pid)
kill -9 $PID
三、在/usr/lib/systemd/system 下编写开机自启脚本
cd /usr/lib/systemd/system
vim new_monitor.service
加入如下内容:
[Unit]
Description=new_monitor_service
After=syslog.target network.target
[Service]
Type=forking
ExecStart=/home/new_monitor/new_monitor-start.sh
ExecStop=/home/new_monitor/new_monitor-stop.sh
PrivateTmp=true
[Install]
WantedBy=multi-user.target
四、启动、停止、开机自启动
systemctl start/stop/enable new_monitor