前言
将项目部署到服务器后,为了方便启动,我们通常会编写一个shell脚本,一键执行启动服务,这样可以为我们节约大量运维成本。
启动方式:sh shell.sh start (sh命令,脚本名称,执行操作)
下面是实际案例分析
#!/bin/sh
BASE_PATH="$(cd `dirname $0`; pwd)"
source "${BASE_PATH}"/env.sh
JAR_PATH="${BASE_PATH}/../jars"
DIR_NAME="`dirname ${BASE_PATH}`"
PACKAGE_NAME="`basename ${DIR_NAME}`"
# 查找从右往左,第一个-,然后截取之前的字符串,比如 mizar-v4.4.0 取出 mizar
PROJECT=${PACKAGE_NAME}
RUN_JARs="`ls ${JAR_PATH}`"
action=$1
if [[ $? != 0 ]]; then
echo '找不到 jars 目录'
exit 1
fi
# 判断启动用户
user="`whoami`"
if [[ "${user}" != "${SHUXI_USER}" ]];then
echo 当前用户为 ${user},启动用户为 ${SHUXI_USER},两者不一致。
echo 请确认登录用户,或者更改配置文件。
exit 1
fi
start()
{
jar=$1
app=${jar%-*}
process="`ps -ef|grep java|grep ${app}|awk '{print $2}'`"
conf_path="${SHUXI_CONF_PATH}/${PROJECT}/bootstrap.${APPLICATION_CONFIG_TYPE}"
if [[ -n ${process} ]];then
echo "程序 ${app} 已经启动,请先手动停止程序。"
exit 1
fi
if [ ! -f ${conf_path} ];then
echo -e "${conf_path} 不存在, 请检查启动脚本中的配置文件路径是否正确或检查文件是否存在.";
exit 1
fi
echo 开始启动程序,${app}
nohup java -Djava.security.egd=file:/dev/./urandom \
${SHUXI_JVM_OPTS} -jar \
-Djasypt.encryptor.password=${JASYPT_PASSWORD} ${JAR_PATH}/${jar} \
--spring.config.location=${conf_path}\
>/dev/null 2>&1 &
sleep 2
ps -ef|grep ${app}|grep -v grep
}
stop()
{
jar=$1
app=${jar%-*}
# 去掉 provider
app=${app%-*}
echo "开始停止程序,${app}"
process="`ps -ef|grep java|grep ${app}|awk '{print $2}'`"
if [[ -n ${process} ]];then
for p in ${process};do
kill ${p}
done
fi
sleep 1
# 防止进程没有退出,强制删除
process="`ps -ef|grep java|grep ${app}|awk '{print $2}'`"
if [[ ! -n ${process} ]];then
echo "${process} 进程还在,强制删除"
for p in ${process};do
kill ${p}
done
fi
echo "完成停止程序,${app}"
}
restart()
{
jar=$1
stop ${jar}
sleep 1
start ${jar}
}
if [ ! $# == 1 ] ;then
echo "参数是 start、stop、restart"
exit;
fi
if [ "${action}" = "start" ] ;then
jar_count=${#RUN_JARs[@]}
if [[ ${jar_count} == 0 ]]; then
echo "找不到 provider 的 jar 包"
exit 1
fi
for jar in ${RUN_JARs}; do
if [[ ${jar} == *data* ]]; then
start ${jar}
fi
done
elif [ "${action}" = "stop" ] ;then
for jar in ${RUN_JARs}; do
if [[ ${jar} == *data* ]]; then
stop ${jar}
fi
done
elif [ "${action}" = "restart" ] ;then
for jar in ${RUN_JARs}; do
if [[ ${jar} == *data* ]]; then
restart ${jar}
fi
done
else
echo "输入的参数是: ${action}, 而不是 [start, stop, restart]"
fi
#!/bin/sh
export SHUXI_CONF_PATH=${SHUXI_CONF_PATH:-/opt/workSpace/conf}
export SHUXI_DATA_PATH=${SHUXI_DATA_PATH:-/data01}
export SHUXI_JVM_OPTS=${SHUXI_JVM_OPTS:- -Xms256m -Xmx256m}
# 如果设置启动用户是 deploy,用其他用户启动会失败。
export SHUXI_USER=${SHUXI_USER:-deploy}
export APPLICATION_CONFIG_TYPE=${APPLICATION_CONFIG_TYPE:-yml}