解决Tomcat因Redis加载慢而启动失败的问题

StartTomcat.py

import subprocess as t
import time, os, requests, sys

WEB_IP = '127.0.0.1:8080'
# WEB_IP = '127.0.0.1'
REDIS_IP = '127.0.0.1'
REDIS_PORT = '18890'


# 获取当前时间
def getCurrentTime():
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


# 检查 Tomcat
def check_Tomcat():
    var = t.getoutput("ps -ef | grep tomcat")
    success = False
    for line in var.split("
"):
        if '/usr/local/tomcat7/conf/logging.properties' in line:
            success = True

    if not success:
        return False

    # 判断是不是 Tomcat僵死掉
    try:
        requests.get("http://" + WEB_IP + "/dsideal_yy/adminlogin/captchaText", timeout=1)
    except requests.exceptions.ConnectTimeout:
        return False
    except requests.exceptions.Timeout:
        return False

    # 判断验证码是不是能正常生成?
    r = requests.get("http://" + WEB_IP + "/dsideal_yy/adminlogin/captchaText")
    if r.status_code != 200:
        return False
    else:
        # 下载图片
        try:
            r = requests.get("http://" + WEB_IP + "/dsideal_yy/adminlogin/captchaImage?text=" + r.json()['text'])
            with open('/usr/local/software/picture.jpg', 'wb') as file:
                file.write(r.content)
            # 用完就删除了吧
            os.remove('/usr/local/software/picture.jpg')
            return True
        except Exception as err:
            print('Tomcat检查发现异常:' + str(err))
            return False


# 重新启动Tomcat
def RestartTomcat():  # 准备了十秒的缓冲时间,用来将mysql和ssdb进行启动应该足够了
    # 开始关闭Tomcat
    cmd = '/usr/local/tomcat7/bin/shutdown.sh'
    os.system(cmd)
    print('正在关闭Tomcat...')
    # 休息5秒
    cmd = "sleep 5"
    os.system(cmd)

    # 查找Tomcat进程并杀死进程
    cmd = "ps -ef | grep 'tomcat' | grep -v grep| awk '{print $2}' | xargs kill -9"
    os.system(cmd)
    print('正在杀掉Tomcat...')
    # 休息5秒
    cmd = "sleep 5"
    os.system(cmd)

    # 重新启动Tomcat
    cmd = '/usr/local/tomcat7/bin/startup.sh'
    os.system(cmd)

    while True:
        r = check_Tomcat()
        if r:
            print('恭喜!Tomcat启动成功!')
            break
        else:
            time.sleep(1)
            print('Tomcat还在启动中,请稍等...' + getCurrentTime())


if __name__ == "__main__":

    # 创建工作目录
    path = '/usr/local/software/CloudPlatformUtil/AutoDeployment/'
    if not os.path.exists(path):
        cmd = 'mkdir -p ' + path
        os.system(cmd)

    # 正常的工作目录
    if os.path.abspath('.') != path:
        print('系统检查到不是在规定的目录下执行,正在拷贝到正确目录下!')
        print(sys.argv[0])
        cmd = 'rm -rf ' + path + (sys.argv[0]).split('/')[-1]
        print(cmd)
        os.system(cmd)
        cmd='cp '+os.path.abspath('.')+'/'+sys.argv[0]+' '+path+sys.argv[0]
        print(cmd)
        os.system(cmd)

    # 执行测试命令
    cmd = 'redis-cli -h ' + REDIS_IP + ' -p ' + REDIS_PORT + ' set a 1'

    while True:
        result = t.getoutput(cmd)
        if 'Connection refused' in result:
            print('redis连接被拒绝,服务没有开启!正在开启...' + getCurrentTime())
            cmd2 = 'service redis start'
            os.system(cmd2)
            time.sleep(1)
        elif 'LOADING Redis is loading the dataset in memory' in result:
            print('redis正在加载中...' + getCurrentTime())
            time.sleep(1)
        else:
            print('redis正常!' + getCurrentTime())
            break

    # 重新启动Tomcat
    RestartTomcat()

    # 替换 /usr/local/tomcat7/bin/startup.sh
    # 检查cron中是否存在本程序的进程
    # 将文件读取到内存中
    foundDownload = False
    with open('/etc/rc.local', "r", encoding="utf-8") as f:
        lines = f.readlines()

    # 删除某行
    with open("/etc/rc.local", "w", encoding="utf-8") as f_w:
        for line in lines:
            if "/usr/local/tomcat7/bin/startup.sh" in line:
                continue
            if "python3 /usr/local/software/CloudPlatformUtil/AutoDeployment/StartTomcat.py" in line:
                continue
            f_w.write(line)

    # 增加某行
    with open('/etc/rc.local', 'a') as f:
        f.write('python3 /usr/local/software/CloudPlatformUtil/AutoDeployment/StartTomcat.py' + '
')

    print('恭喜,所有动作成功完成!')
原文地址:https://www.cnblogs.com/littlehb/p/7645118.html