Shell 代码之启停查 Java 服务

1. 启动

1. 无额外加载

不加载额外的 libs 直接启动

1
2
3
#! /bin/bash
cd /home/app/service
nohup java -cp .:log4j.properties:sysconfig.properties:my-package-0.0.1-SNAPSHOT.jar com.demo.Main $@ &

2. 有额外加载

加载额外的 libs 和 conf 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#! /bin/bash
CUR_DIR=$(cd $(dirname $0);pwd)
APP_HOME=$(dirname ${CUR_DIR})
#echo ${APP_HOME}
CLASS_PATH=${APP_HOME}/conf:${APP_HOME}/libs/*
MAIN_CLASS=com.demo.JobApplication
LOG_DIR=${APP_HOME}/logs
LOG_FILE=${LOG_DIR}/my.log

if [ ! -d ${LOG_DIR} ];then
mkdir -p ${LOG_DIR}
fi
if [ ! -f ${LOG_FILE} ];then
touch ${LOG_FILE}
fi

exec nohup java -cp ${CLASS_PATH} ${MAIN_CLASS} $@ > /dev/null 2>${LOG_FILE} 2>&1 &
echo "========== Apploation started =========="

2. 停止

保证进程获取的只有1个,否则需要手动选择停止,防止误停止

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#! /bin/bash
MAIN_CLASS=com.demo.JobApplication
PID=$(ps -ef|grep -v grep|grep ${MAIN_CLASS}|awk '{print $2}')
arr=()
for line in ${PID}
do
arr[${#arr[*]}]=${line}
done
if [ ${#arr[*]} -eq 0 ]
then echo "==========WARN : Process is stopped, skip stop applicatrion=========="
exit 0
fi

if [ ${#arr[*]} -gt 1 ]
then echo "==========ERROR : Same process more than one, please check you applicatrion=========="
exit -1
fi

kill ${arr[0]}
if [ $? != 0 ]
then echo "==========ERROR : stop fail=========="
else
echo "==========SUCCESS : stop succeed=========="
fi

3. 查询状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#! /bin/bash
MAIN_CLASS=com.demo.JobApplication
RST=$(ps -aux|grep -v grep|grep ${MAIN_CLASS})

if [[ -z ${RST} ]]
then echo "========== Applicatrion not running =========="
exit 0
fi

arr=()
for line in ${RST}
do
arr[${#arr[*]}]=${line}
done
echo "User : ${arr[0]}"
echo "PID : ${arr[1]}"
echo "CPU : ${arr[2]}"
echo "MEM : ${arr[3]}"
echo "VSZ : ${arr[4]}"
echo "RSS : ${arr[5]}"
echo "TTY : ${arr[6]}"
echo "STAT : ${arr[7]}"
echo "START : ${arr[8]}"
echo "TIME : ${arr[9]}"
start=10
end=${#arr[@]}
num=end-start
echo "CMD : ${arr[@]:$start:$end}"