实现 Spring Boot 应用程序jar包开机自动启动

1. 创建启动脚本

为了确保Spring Boot应用程序能够顺利启动,我们需要创建一个启动脚本。该脚本将负责检查并关闭已存在的应用实例(如果存在),然后以指定的配置重新启动应用。

1.1 编写启动脚本

使用vim编辑器创建名为test01-api-startup.sh的脚本文件:

vim test01-api-startup.sh

在打开的编辑器中输入以下内容:

!/bin/bash


# 设置环境变量,防止构建过程中的误杀
BUILD_ID=DONTKILLME

# 定义日志文件路径
log_file="/data/log/test01-api-reboot.log"

# 指定活动的Spring配置文件
active_profile="prod"

# 输出重启信息
echo "Restarting SpringBoot Application" >> $log_file

# 获取正在运行的应用程序PID
pid=$(ps -ef | grep test01-api-0.0.1-SNAPSHOT.jar | grep -v grep | awk '{print $2}')

# 如果PID存在,则杀死进程
if [ -n "$pid" ]; then
    kill -9 $pid
    echo "关闭test01-api进程:$pid" >> $log_file
fi

# 输出重启执行信息
echo "重启执行....." >> $log_file

# 以守护进程方式启动应用程序,并指定活动配置文件
nohup java -jar /data/test01-source/api/test01-api-0.0.1-SNAPSHOT.jar --spring.profiles.active=$active_profile &

# 记录启动完成信息
echo "test01-api启动完毕.....active_profile: $active_profile" >> $log_file

1.2 保存并退出编辑器

输入:wq保存文件并退出vim编辑器。

1.3 赋予脚本执行权限

chmod 777 test01-api-startup.sh

2. 创建systemd服务文件

为了让应用能够在系统启动时自动运行,我们需要创建一个systemd服务文件。

2.1 切换到systemd服务目录

cd /etc/systemd/system/

2.2 创建服务文件

使用vim编辑器创建名为test01-api-reboot.service的服务文件:

vim test01-api-reboot.service

2.3 编写服务文件内容

在打开的编辑器中输入以下内容:

[Unit]
Description=Manage test01-api
After=network.target

[Service]
Type=forking
ExecStart=/data/bin/test01-api-startup.sh

[Install]
WantedBy=multi-user.target

2.4 保存并退出编辑器

输入:wq保存文件并退出vim编辑器。

2.5 赋予服务文件执行权限

chmod 755 /etc/systemd/system/test01-api-reboot.service

2.6 启用服务

使服务在系统启动时自动启动:

systemctl enable test01-api-reboot

2.7 启动服务

手动启动服务以立即运行:

systemctl start test01-api-reboot

2.8 检查服务状态

查看服务当前的状态以确认其是否正确运行:

systemctl status test01-api-reboot

3. 查看日志

3.1 脚本日志

tail -200f /data/log/test01-api-reboot.log

3.2 应用程序日志

tail -200f /data/log/api/log.log

重启电脑,自启动成功,查看日志正常,完成配置。

posted @ 2025-01-14 10:48  哈喽哈喽111111  阅读(322)  评论(0)    收藏  举报