命令行方式啟動(dòng)和停止jar
在Linux系統(tǒng)中,可以使用以下命令啟動(dòng)jar文件:
java -jar your-application.jar
要在后臺(tái)運(yùn)行jar文件,可以使用nohup命令:
nohup java -jar your-application.jar > output.log 2>&1 &
停止jar進(jìn)程可以使用kill命令:
kill $(pgrep -f your-application.jar)
使用Shell腳本管理jar
創(chuàng)建一個(gè)名為manage-jar.sh的shell腳本:
#!/bin/bash
JAR_NAME="your-application.jar"
PID_FILE="app.pid"
start() {
nohup java -jar $JAR_NAME > output.log 2>&1 & echo $! > $PID_FILE
echo "應(yīng)用已啟動(dòng),PID: $(cat $PID_FILE)"
}
stop() {
if [ -f $PID_FILE ]; then
kill $(cat $PID_FILE)
rm $PID_FILE
echo "應(yīng)用已停止"
else
echo "PID文件不存在,應(yīng)用可能未運(yùn)行"
fi
}
case "$1" in
start) start ;;
stop) stop ;;
restart) stop; start ;;
*) echo "用法: $0 {start|stop|restart}" ;;
esac
使用方法:./manage-jar.sh {start|stop|restart}
使用systemd服務(wù)管理jar
創(chuàng)建一個(gè)systemd服務(wù)文件 /etc/systemd/system/myapp.service:
[Unit]
Description=My Java Application
After=network.target
[Service]
ExecStart=/usr/bin/java -jar /path/to/your-application.jar
User=youruser
Type=simple
Restart=on-failure
RestartSec=10
[Install]
WantedBy=multi-user.target
使用systemctl命令管理服務(wù):
- 啟動(dòng):sudo systemctl start myapp
- 停止:sudo systemctl stop myapp
- 重啟:sudo systemctl restart myapp
- 查看狀態(tài):sudo systemctl status myapp
注意事項(xiàng)
在生產(chǎn)環(huán)境中,建議使用systemd服務(wù)來(lái)管理jar應(yīng)用,因?yàn)樗峁┝烁玫倪M(jìn)程管理和自動(dòng)重啟功能。對(duì)于開發(fā)環(huán)境或臨時(shí)需求,shell腳本方式更為靈活。無(wú)論選擇哪種方法,都要確保正確設(shè)置Java環(huán)境變量和必要的權(quán)限。