nginx 端检测 tomcat 应用 热切换

2017年12月20日 1 条评论 1.63k 次阅读 1 人点赞

(临时方案)nginx前端配置upstream中指定2个tomcat应用,检测当其中挂掉一个的时候,自动切换到另外一个。

修改其中的 ip:port

#!/bin/bash
path1=$(cd `dirname $0`; pwd)
nginx_conf=/usr/local/nginx/conf/vhost/test.conf
nginx_bin=/usr/local/nginx/sbin/nginx
if [ ! -f ems_hotback.log ]; then touch ems_hotback.log;fi
code=401
mail_list="[email protected]"
date1=`date "+%Y-%m-%d %H:%M:%S"`
arg12=`cat -n ${nginx_conf} |grep -w "ip:ports"`
arg13=`cat -n ${nginx_conf} |grep -w "ip:ports"`
arg12_1=`echo ${arg12} | awk -F ' ' '{print $1}'`
arg12_2=`echo ${arg12} | awk -F ' ' '{print $2}'`
arg12_3=`echo ${arg12} | awk -F ' ' '{print $3}'`
arg12_3=${arg12_3%?}
arg13_1=`echo ${arg13} | awk -F ' ' '{print $1}'`
arg13_2=`echo ${arg13} | awk -F ' ' '{print $2}'`
arg13_3=`echo ${arg13} | awk -F ' ' '{print $3}'`
arg13_3=${arg13_3%?}

function date_now(){
  echo  `date "+%Y-%m-%d %H:%M:%S"` $1 >> ${path1}/ems_hotback.log
}
function curl_head(){
  now_code1=0
  now_code1=`curl -I -s --connect-timeout 5 -m 5 -o /dev/null -w %{http_code} http://${1}/emsserver/`
  echo ${now_code1}
  #return ${now_code1}
}
function mail_do(){
  for mail_name in `echo ${mail_list}`;do
    echo "故障时间:${date1} 
 故障节点:http://${1}/emsserver/ 
切换节点:http://${2}/emsserver/ 
来自于主机:192.168.25.39" | mutt -s "故障切换:由${1}切换为${2}" -e 'set content_type="text/html"' ${mail_name}
  done
}
if [[ "${arg12_2}" == "server" ]];then
  date_now "当前使用服务 ${arg12_3}"
  code_now=`curl_head "${arg12_3}"`
  date_now "服务 ${arg12_3} 的状态码检测结果为 ${code_now}"
  if [[ ${code_now} != ${code} ]];then
    sed -i "s/${arg13_2} ${arg13_3}/server ${arg13_3}/g" ${nginx_conf}
    sed -i "s/${arg12_2} ${arg12_3}/#server ${arg12_3}/g" ${nginx_conf}
    date_now "替换 ${nginx_conf} 中使用 ${arg13_3}"
    ${nginx_bin} -s reload
    date_now "重启服务 ${nginx_bin}"
    mail_do ${arg12_3} ${arg13_3}
    date_now "发送提醒邮件信息给 ${mail_list}"
  else
    date_now "检测结果正常……" 
  fi
elif [[ "${arg13_2}" == "server" ]];then
  date_now "当前使用服务 ${arg13_3}"
  code_now=`curl_head ${arg13_3}`
  date_now "服务 ${arg13_3} 的状态码检测结果为 ${code_now}"
  if [[ ${code_now} != ${code} ]];then
    sed -i "s/${arg12_2} ${arg12_3}/server ${arg12_3}/g" ${nginx_conf}
    sed -i "s/${arg13_2} ${arg13_3}/#server ${arg13_3}/g" ${nginx_conf}
    date_now "替换 ${nginx_conf} 中使用 ${arg12_3}"
    ${nginx_bin} -s reload
    date_now "重启服务 ${nginx_bin}"
    mail_do ${arg13_3} ${arg12_3}
    date_now "发送提醒邮件信息给 ${mail_list}"
  else
    date_now "检测结果正常……"
  fi
fi

Sevenfal

这个人太懒什么东西都没留下

文章评论(1)

  • sevenfal

    需要在重启前判断另外一个应用是否正常,如果正常就重启,不正常就不重启,防止反复重启。

    2018年1月15日