linux上启动jar,通常要使用nohup等命令,指定jdk和jar的地址,下面进行封装shell脚本,集成启动、停止、重启、查看状态等操作
本shell脚本只指定应用端口,jar地址,jdk地址进行应用启停控制,后续优化指定gc等配置
#!/bin/sh
port=8081 #定义变量等号左右不能有空格
jar_name=/usr/local/software/system-2.4.0.jar
#运行脚本提示信息
tips(){
echo "-------------------------------------"
echo ""
echo "项目端口: ${port}"
echo "项目地址: ${jar_name}"
echo ""
echo "你可以使用如下参数进行操作"
echo "-status -查看当前项目运行状态"
echo "-start -启动当前项目"
echo "-stop -停止当前项目"
echo "-restart -重启当前项目"
echo ""
echo "-------------------------------------"
}
#查看状态
status(){
#查询端口的PID {print $7}-取出打印的第七个值
pid=`netstat -apn |grep $port |awk '{print $7}' |cut -d/ -f 1`
#判断端口是否被占用
if [ -z "${pid}" ];then
echo "没有项目在运行"
else
echo "项目正在运行中"
fi
}
#启动项目
start(){
pid=`netstat -apn |grep $port |awk '{print $7}' |cut -d/ -f 1`
if [ -z "${pid}" ];then
echo "正在启动......"
nohup /srv/program/jdk1.8.0_191/bin/java -jar /usr/local/software/system-2.4.0.jar >/dev/null 2>&1 &
else
echo "项目运行中或端口已被占用"
fi
}
#停止项目
stop(){
pid=`netstat -apn |grep $port |awk '{print $7}' |cut -d/ -f 1`
if [ -z "${pid}" ];then
echo "没有项目在运行,请先启动"
else
kill -9 $pid
echo "已杀死端口为 ${port} 的应用"
fi
}
#重启项目
restart(){
pid=`netstat -apn |grep $port |awk '{print $7}' |cut -d/ -f 1`
echo "正在杀死端口 ${port} 的pid ${pid} 中..."
if [ -z "${pid}" ];then
echo "项目未启动"
else
kill -9 $pid
fi
sleep 5 #睡眠五秒
start #调用启动方法
echo "项目重启成功!"
}
#参数选项
case "$1" in
"-status")
status
;;
"-start")
start
;;
"-stop")
stop
;;
"-restart")
restart
;;
*)
tips
;;
esac
优化:指定垃圾收集器等参数,可自由扩展
#指定垃圾回收器和Gc日志
nohup /srv/program/jdk1.8.0_191/bin/java -Xmx2g -Xms2g -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -Xloggc:/srv/program/gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/srv/program/ -jar /srv/program/software.jar >/dev/null 2>&1 &