1 #!/bin/bash 2 3 JAVA_HOME=/usr/java/default 4 5 #java虚拟机启动参数 6 JAVA_OPTS="-server -Xms800m -Xmx800m -Xmn256m -Xss256k -XX:PermSize=256M -XX:MaxPermSize=512M -XX:SurvivorRatio=8 -XX:MaxTenuringThreshold=5 -XX:GCTimeRatio=19 -Xnoclassgc -XX:+DisableExplicitGC -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+UseCMSCompactAtFullCollection -XX:CMSFullGCsBeforeCompaction=0 -XX:-CMSParallelRemarkEnabled -XX:CMSInitiatingOccupancyFraction=70 -XX:SoftRefLRUPolicyMSPerMB=0 -XX:+PrintClassHistogram -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintHeapAtGC -Xloggc:/data/logs/newslib-app-api/gc.log " 7 8 #这里可替换为你自己的执行程序,其他代码无需更改 9 APP_NAME=video.jar 10 APP_USER=tomcat 11 12 #SHUTDOWN_WAIT is wait time in seconds for java proccess to stop 13 SHUTDOWN_WAIT=90 14 15 workdir=$(cd $(dirname $0); pwd) 16 17 #使用说明,用来提示输入参数 18 usage() { 19 echo "Usage: sh 执行脚本.sh [start|stop|restart|status]" 20 exit 1 21 } 22 23 #检查程序是否在运行 24 is_exist(){ 25 pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}' ` 26 #如果不存在返回1,存在返回0 27 if [ -z "${pid}" ]; then 28 return 1 29 else 30 return 0 31 fi 32 } 33 34 # @args <beg> <end> 35 # return random integer in [<beg>, <end>) 36 function random_range() { 37 local beg=$1 38 local end=$2 39 echo $((RANDOM % ($end - $beg) + $beg)) 40 } 41 42 #启动方法 43 start(){ 44 is_exist 45 if [ $? -eq "0" ]; then 46 echo "${APP_NAME} is already running. pid=${pid} ." 47 else 48 #port=$(random_range 30000 60000) 49 port=8004 50 nohup java $JAVA_OPTS -jar $workdir/$APP_NAME --server.port=$port > /dev/null 2>&1 & 51 is_exist 52 if [ $? -eq "0" ]; then 53 echo "${APP_NAME} started. pid=${pid}, port=$port." 54 fi 55 fi 56 } 57 58 #停止方法 59 stop(){ 60 is_exist 61 if [ $? -eq "0" ]; then 62 kill $pid 63 64 65 let kwait=$SHUTDOWN_WAIT 66 count=0; 67 until [ `ps -p $pid | grep -c $pid` = '0' ] || [ $count -gt $kwait ] 68 do 69 echo -n -e " e[00;31mwaiting for processes to exite[00m"; 70 sleep 1 71 let count=$count+1; 72 done 73 74 if [ $count -gt $kwait ]; then 75 echo -n -e " e[00;31mkilling processes didn't stop after $SHUTDOWN_WAIT secondse[00m" 76 kill -9 $pid 77 fi 78 79 echo "${APP_NAME} stoped." 80 else 81 echo "${APP_NAME} is not running" 82 fi 83 } 84 85 #输出运行状态 86 status(){ 87 is_exist 88 if [ $? -eq "0" ]; then 89 echo "${APP_NAME} is running. Pid is ${pid}" 90 else 91 echo "${APP_NAME} is NOT running." 92 fi 93 } 94 95 #重启 96 restart(){ 97 stop 98 start 99 } 100 101 #根据输入参数,选择执行对应方法,不输入则执行使用说明 102 case "$1" in 103 "start") 104 start 105 ;; 106 "stop") 107 stop 108 ;; 109 "status") 110 status 111 ;; 112 "restart") 113 restart 114 ;; 115 *) 116 usage 117 ;; 118 esac