Linux设置java项目开机自启动

创建脚本文件,并赋权限

#!/bin/sh
# java项目jar包所在位置,demo为jar名称
cd /usr/local/src/demo
pid=`ps -ef|grep 'demo.jar*'|grep -v grep|awk '{print $2}'`
if [ -n "${pid}" ];then
	kill -9 ${pid}
	echo "Process demo killed!"
	nohup java -Dspring.profiles.active=prod -server -Xms128m -Xmx256m -XX:CompressedClassSpaceSize=128m -XX:MetaspaceSize=200m -XX:MaxMetaspaceSize=200m -jar demo.jar > ./demo.log &
	echo "ReStart demo Success!"
        tail -100f /usr/local/src/demo/demo.log
else
	nohup java -Dspring.profiles.active=prod -server -Xms128m -Xmx256m -XX:CompressedClassSpaceSize=128m -XX:MetaspaceSize=200m -XX:MaxMetaspaceSize=200m -jar demo.jar > ./demo.log &
	echo "Start demo Success!"
        tail -100f /usr/local/src/demo/demo.log
fi

chmod 777 demo.sh

接下来,设置自启动有两种方式:

方式一:修改开机启动项配置

找到rc.local 脚本,一般路径

cd /etc/rc.local

在rc.local添加脚本的绝对路径,就可以了

#!/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

/usr/local/src/demo/demo.sh >/tmp/demo.log 2>&1

同样的,rc.local与demo.sh脚本文件一样,都需要赋权。

方式二:注册服务

#创建相关服务文件
vim /etc/systemd/system/demo.service

服务文件内容:

[Unit]
Description=demo-service
After=network.target

[Service]
Type=forking
#ExceStart 为启动命令  请确认 启动地址和路径等等
ExecStart=/usr/local/src/demo/demo.sh

[Install]
WantedBy=multi-user.target

设置为服务

#重载系统服务
systemctl daemon-reload
#测试 服务是否生效   
systemctl  start  demo.service  
ps aux|grep demo
 
# 设置服务为开机启动服务
systemctl enable demo.service
 
#开机服务查询
systemctl list-units --type=service

注意:脚本文件一定要赋予权限

你可能感兴趣的:(工具,linux,jvm,java)