使用shell脚本编排微服务. 解决依赖问题
#!/bin/bash
# 基本参数
pid=0
: ${SLEEP_SECOND:=2}
JVM_OPTS=" -Xms128M -Xmx128M "
BASE_PATH="./build/libs"
# jar 包路径
EUREKA="${BASE_PATH}/xxx-cloud-eureka-1.0.0.jar"
CONFIG="${BASE_PATH}/xxx-cloud-config-1.0.0.jar"
GETAWAY="${BASE_PATH}/xxx-cloud-gateway-1.0.0.jar"
# 微服务
MICRO=(${EUREKA} ${CONFIG} ${GETAWAY} )
# 依赖关系
DEPEND_ON='[{"service":"config", "host":"127.0.0.1", "port": 17031,"sleep": 2},
{"service":"gateway", "host":"127.0.0.1","port": 17032,"sleep": 30}]'
# json values
SERVICE_NAME=(`echo ${DEPEND_ON} | jq '.[] | .service'`)
wait_for() {
echo Waiting for $1 to listen on $2...
while ! nc -z $1 $2; do echo waiting...; sleep ${SLEEP_SECOND}; done
}
depend_on_check(){
for s_name in "${SERVICE_NAME[@]}"
do
ss_name=`eval echo ${s_name}`
if [[ $1 =~ ${ss_name} ]];then
singe_json=`echo ${DEPEND_ON} | jq ".[] | select(.service == ${s_name})"`
host=`echo ${singe_json} | jq '.host'`
port=`echo ${singe_json} | jq '.port'`
sleep=`echo ${singe_json} | jq '.sleep'`
wait_for `eval echo ${host}` ${port}
sleep ${sleep}
fi
done
}
start_micro(){
nohup java -jar ${JVM_OPTS} $1 >/dev/null 2>log &
}
stop_micro(){
echo "$1 pid $2 stop..."
kill -15 $2
}
gradle_build(){
./gradlew clean build
}
gradle_clean(){
./gradlew clean
}
check_pid(){
pid=`ps -ef |grep $1 |grep -v grep |awk '{print $2}'`
}
start(){
#gradle_build
for service in "${MICRO[@]}"
do
check_pid ${service}
if [[ ! -n "${pid}" ]]; then
depend_on_check ${service}
start_micro ${service}
else
echo "${service} Is Running PID: $pid"
fi
done
}
stop(){
#gradle_clean
for service in "${MICRO[@]}"
do
check_pid ${service}
if [[ -n "${pid}" ]]; then
stop_micro ${service} ${pid}
else
echo "${service} Is Not Running"
fi
done
}
restart(){
stop
start
}
status(){
for service in "${MICRO[@]}"
do
check_pid ${service}
if [[ ! -n "${pid}" ]]; then
echo "${service} Is Not Running"
else
echo "${service} Is Running PID: $pid"
fi
done
}
main(){
# 检查jq 是否安装
if ! [[ -x "$(command -v jq)" ]]; then
echo 'Error: jq is not installed.' >&2
exit 1
fi
# 参数匹配
case $1 in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
status)
status
;;
*)
echo "require start|stop|restart|status and jq (parse json lib)"
exit 1
;;
esac
}
main "$@"
使用
./run.sh start
./run.sh stop
./run.sh status