0

我有一个微服务,只有在另一台服务器启动时才需要完成一项工作。几个星期以来它工作得很好,如果服务器关闭,微服务会在没有完成工作的情况下(应该)休眠一点,如果服务器启动 - 工作就完成了。服务器永远不会关闭超过几分钟(当然!服务器受到高度监控),因此该作业被跳过 2-3 次。

今天我进入我的 Docker 容器,并在日志中注意到该作业现在甚至没有尝试继续几个星期(我知道不监控的错误选择),这表明我认为发生了某种死锁。我还假设问题出在我的异常处理上,可以使用我独自工作的一些建议。

def is_server_healthy():
    url = "url" #correct url for health check path
    try:
        res = requests.get(url)
    except Exception as ex:
        LOGGER.error(f"Can't health check!{ex}")
    finally:
        pass

    return res

def init():
    while True:
        LOGGER.info(f"Sleeping for {SLEEP_TIME} Minutes")
        time.sleep(SLEEP_TIME*ONE_MINUTE)

        res = is_server_healthy()

        if res.status_code == 200:
            my_api.DoJob()
            LOGGER.info(f"Server is: {res.text}")
        else:
            LOGGER.info(f"Server is down... {res.status_code}")

(变量名称已更改以简化问题)

健康检查很简单——如果 up 则返回“up”。其他任何东西都被认为是关闭的,所以除非状态 200 和“up”回来,否则我认为服务器已关闭。

4

1 回答 1

2

如果您的服务器关闭,您会收到未捕获的错误:

NameError: name 'res' is not defined

为什么?看:

def is_server_healthy():
    url = "don't care"
    try:
        raise Exception()  # simulate fail
    except Exception as ex:
        print(f"Can't health check!{ex}")
    finally:
        pass

    return res   ## name is not known ;o)

res = is_server_healthy()
if res.status_code == 200:   # here, next exception bound to happen
    my_api.DoJob()
    LOGGER.info(f"Server is: {res.text}")
else:
    LOGGER.info(f"Server is down... {res.status_code}")

即使您声明了名称,它也会尝试访问一些不存在的属性:

if res.status_code == 200:   # here - object has no attribute 'status_code'   
    my_api.DoJob()
    LOGGER.info(f"Server is: {res.text}")
else:
    LOGGER.info(f"Server is down... {res.status_code}")

会尝试访问一个根本不存在的成员 => 异常,并且进程消失了。


您最好使用某种特定于系统的方式每分钟调用一次脚本(Cron Jobs,Task Scheduler),然后在while True:睡眠中闲置。

于 2020-03-26T13:19:37.523 回答