我们在项目中都会遇到项目打包,可以通过assembly对我们的项目进行打包。
针对打包构建jar包,本文不再叙述。具体可以参考maven插件assembly使用及springboot启动脚本start.sh和停止脚本 stop.sh
这里面已经有一个springboot 的启动脚本了,本文之所以还要写,是因为之前的脚本存在一个问题。关闭脚本的时候是通过kill -9 命令进行的,但其实我们项目中可能很多时候不能强制关闭的,在关闭之前需要做一些事情。比如将内存数据存到磁盘,dubbo清空zookeeper里面的固定节点 等等。
这里将启动脚本环境变量抽出来作为一个文件来使用:
setenv.sh
#!/usr/bin/env bash
PIDFILE=server.pid
if [ "$JAVA_HOME" != "" ]; then
JAVA="$JAVA_HOME/bin/java"
else
JAVA=java
fi
JAVA_OPTS="-server -Xms32m -Xmx32m -Xmn24m -Xss256K -XX:MetaspaceSize=10m -DHADOOP_USER_NAME=root
-XX:SurvivorRatio=4 -XX:+UseConcMarkSweepGC \
-XX:+UseCMSCompactAtFullCollection -XX:CMSFullGCsBeforeCompaction=10 \
-XX:CMSInitiatingOccupancyFraction=60 -XX:+AggressiveOpts \
-XX:+UseFastAccessorMethods \
-XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=$base_dir/dump.dump
-XX:+PrintGCDateStamps -XX:+PrintGCDetails \
-Xloggc:$base_dir/gc.log"
start.sh 启动脚本:
#!/usr/bin/env bash
#source $(dirname $0)/../../env.sh
SERVERJAR="database-project-0.0.1-SNAPSHOT.jar"
base_dir=$(dirname $0)
cd ..
if [ -r "$base_dir/setenv.sh" ]; then
. "$base_dir/setenv.sh"
fi
PID=$(ps -ef | grep "$SERVERJAR" | grep -v grep | awk '{ print $2}')
if [ -z "$PID" ]; then
echo "Application has already stopped."
else
echo "kill $PID"
kill $PID && echo "Send stopping signal to server successful."
#wait server stop
LOOPS=0
while(true)
do
PID=$(ps -ef | grep "$SERVERJAR" | grep -v grep | awk '{print $2}')
if [ -z "$PID" ]; then
echo "Stop server successful! Cost $LOOPS seconds."
break;
fi
#judge time out
if [ "$LOOPS" -gt 180 ]; then
echo "$Stop server cost time over 180 seconds. Now force stop it."
kill -9 $PID && echo "Force stop successful."
break;
else
echo "Cost $LOOPS seconds."
fi
let LOOPS=LOOPS+1
sleep 1
done
fi
echo `pwd`
echo $SERVERJAR
echo $JAVA
echo $JAVA_OPTS
echo $JAVA_DEBUG_OPT
nohup $JAVA $JAVA_OPTS -jar $base_dir/../lib/$SERVERJAR > $base_dir/nohup.out 2>&1 < /dev/null &
if [ $? -eq 0 ]; then
echo -n $! > "$PIDFILE"
if [ $? -eq 0 ]; then
sleep 1
echo "STARTED"
else
echo "FAILED TO WRITE PID"
exit 1
fi
else
echo "SERVER DID NOT START"
exit 1
fi
stop.sh 脚本
#!/usr/bin/env bash
#source $(dirname $0)/../../env.sh
SERVERJAR="database-project-0.0.1-SNAPSHOT.jar"
base_dir=$(dirname $0)
cd ..
if [ -r "$base_dir/setenv.sh" ]; then
echo -e "come get data start"
. "$base_dir/setenv.sh"
echo -e "come get data end "
fi
PID=$(ps -ef | grep "$SERVERJAR" | grep -v grep | awk '{ print $2}')
if [ -z "$PID" ]; then
echo "Application has already stopped."
else
echo "kill $PID"
kill $PID && echo "Send stopping signal to server successful."
#wait server stop
LOOPS=0
while(true)
do
PID=$(ps -ef | grep "$SERVERJAR" | grep -v grep | awk '{print $2}')
if [ -z "$PID" ]; then
echo "Stop server successful! Cost $LOOPS seconds."
break;
fi
#judge time out
if [ "$LOOPS" -gt 180 ]; then
echo "$Stop server cost time over 180 seconds. Now force stop it."
kill -9 $PID && echo "Force stop successful."
break;
else
echo "Cost $LOOPS seconds."
fi
let LOOPS=LOOPS+1
sleep 1
done
fi