通过shell脚本对Java服务启停进行控制。支持单个服务和多个服务的
start
、stop
、status
、restart
。支持自定义启动命令。(不限于Java服务,适用于各类通过命令行启动的服务)
脚本名称为 runjar.sh
, 底部提供源码。通过三部分进行说明:操作说明
、维护自定义服务列表
、脚本源码
操作说明
-
查看可执行的命令
./runjar.sh
-
启动单个服务
./runjar.sh start 服务名
(已经处于运行状态的服务不会重复运行并提示进程号) -
查看单个服务的运行状态
./runjar.sh status 服务名
-
停止单个服务
./runjar.sh stop 服务名
-
批量启动服务
./runjar.sh start
-
批量停止服务
./runjar.sh stop
-
批量查看各个服务的状态
./runjar.sh status
维护自定义服务列表
-
新建
runjar.txt
文件放到runjar.sh
脚本的同级目录。 -
自定义服务的启动命令
启动命令 === 自定义服务名称
,每个服务占据一行,启动命令和自定义服务名之间用===
隔开,所有的启停操作通过自定义的服务名称进行。例如:/home/jdk1.8/bin/java -jar /home/myjar/jarzip.jar === jarzip /home/jdk1.8/bin/java -jar /home/myjar/jarzip2.jar === myzip
脚本源码
#!/bin/bash
function getcmdbyline(){
command=`echo $1 | awk 'BEGIN {FS="==="} {print $1}' | tr -d '\r\n' | tr -d '\n'`
echo $command
}
function getappid(){
id=`echo $1 | awk 'BEGIN {FS="==="} {print $2}' | tr -d '\r\n' | tr -d '\n'` # 防止使用 CRLF文件出现的问题
echo $(echo $id)
}
CONFIG_FILE="./runjar.txt" # 可自定义配置文件名称
function getcmdbyfile(){
cat $CONFIG_FILE | while read line || [[ -n ${line} ]]
do
command=`getcmdbyline "$line"`
appid=`getappid "$line"`
if [ $appid == $1 ]
then
echo $command
break
fi
done
}
function isrunning(){
cmd=`getcmdbyfile $1`
if [ -n "$cmd" ]
then
num=`ps aux|grep "$cmd" | wc -l`
if [ $num -gt 1 ]
then
ps -ef | grep "$cmd" | grep -v grep | grep -v "$0" | awk '{print $2}'
fi
fi
}
function operservice(){
if [ $1 == "start" ]
then
echo "start $2..."
cmd=`getcmdbyfile $2`
if [ -n "$cmd" ]
then
isrun=`isrunning $2`
if [ -n "$isrun" ]
then
echo "app is already running, don't start again , service id is $isrun"
else
nohup ${cmd} 2>&1 & > null
echo "done"
fi
else
echo "not found cmd"
fi
fi
if [ $1 == "stop" ]
then
echo "stop $2..."
isrun=`isrunning $2`
if [ -n "$isrun" ]
then
kill -9 $isrun
echo "kill done"
else
echo "app not run, not need to kill"
fi
fi
if [ $1 == "restart" ]
then
echo "restart $2"
cmd=`getcmdbyfile $2`
if [ -n "$cmd" ]
then
isrun=`isrunning $2`
if [ -n "$isrun" ]
then
kill -9 $isrun
echo "stop done"
fi
nohup ${cmd} 2>&1 &
echo "start done"
else
echo "not found cmd, please config."
fi
fi
if [ $1 == "status" ]
then
echo "status $2"
isrun=`isrunning $2`
if [ -n "$isrun" ]
then
echo "app is running , service id is $isrun"
else
echo "app not running."
fi
fi
}
if [ ! -n "$1" ]
then
echo "Usage: ./runjar { start | stop | restart | status }"
else
if [ ! -n "$2" ]
then
cat $CONFIG_FILE | while read line || [[ -n ${line} ]]
do
# command=`getcmdbyline "$line"` # 将 $line 整体作为一个参数
appid=`getappid "$line"`
echo "####### $appid #######"
operservice $1 $appid
echo "done"
done
else
operservice $1 $2
fi
fi