【Linux】Java程序开机自启原创
# 1 前言
在当今的数字化时代,确保关键应用程序的持续运行对于业务的稳定性和可靠性至关重要。
特别是对于Java应用程序来说,无论是因为计划内的维护还是意外的服务器断电,都需要能够迅速、自动地重启,以最小化服务中断的影响。
本文将向您展示如何实现Java程序在服务器断电后的自动重启,确保您的服务能够在遇到不可预见的中断后快速恢复。
# 2 Jar包通用启动脚本
#!/bin/bash
# Configuration
spring_profiles_active="prod" # 设置配置文件激活的环境
jar_path="/opt/myxm/webjar" # JAR 文件的路径(根据实际情况修改)
jar_name="test.jar" # JAR 文件名称(根据实际情况修改)
# Complete path to the JAR
full_jar_path="$jar_path/$jar_name"
# Dynamically generate log file name from the JAR name
log_file="${jar_name%.jar}.log"
# This script kills the previous instance of the JAR if running,
# then starts a new instance in the background, and tails the log.
# Kill the previous process
pids=$(pgrep -f "$full_jar_path")
for pid in $pids; do
if [ -n "$pid" ]; then
echo "Killing previous process: $pid"
kill "$pid" # 优雅地终止进程
sleep 5 # 等待一段时间,给进程一些清理和退出的时间
# 检查进程是否仍然存在,如果存在,则使用 kill -9 强制终止
if kill -0 "$pid" 2>/dev/null; then
echo "Process $pid did not terminate, forcing kill."
kill -9 "$pid"
fi
fi
done
# Start the new process in the background and redirect output to a log file
nohup java -jar $full_jar_path --spring.profiles.active="$spring_profiles_active" > $log_file 2>&1 &
# View the log
tail -f $log_file
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# 3 开机自启-方法1:systemd
在/etc/systemd/system/目录下新建文件:start_myxm.service
[Unit]
Description=myxm start script
[Service]
WorkingDirectory=/opt/myxm/webjar
ExecStart=/bin/bash /opt/myxm/webjar/start.sh
Type=simple
Restart=on-failure
[Install]
WantedBy=multi-user.target
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# 3.1 使脚本文件生效
sudo systemctl daemon-reload
1
# 3.2 启动自定义脚本服务
sudo systemctl start start_myxm.service
1
# 3.3 设置开机自启
sudo systemctl enable start_myxm.service
1
# 3.4 查看启动状态
sudo systemctl status start_myxm.service
1
# 4 开机自启-方法2:crontab【推荐】
在 crontab -e 中配置
@reboot /bin/sh /opt/myxm/webjar/start.sh
1
上次更新: 2024/02/08, 02:03:58