在开始烧瓶之前如何检查redis是否正在运行(如果不是则启动它)?

时间:2014-02-11 16:57:37

标签: python redis flask

我是Flask的新手,想要确保redis服务器正在运行,如果不是,则启动它。这就是我所拥有的:

@app.before_first_request
def initialize():
  cmd = 'src/redis-cli ping'
  p = subprocess.Popen(cmd,stdout=subprocess.PIPE)
  out, err = p.communicate()
  #if out.startswith('Could not connect to Redis'): #start redis here
  if err is not None: raise Exception(err)

但是,我收到错误“OSError:[Errno 2]没有这样的文件或目录”

有没有更简单的方法来检查redis服务器是否正在运行?

2 个答案:

答案 0 :(得分:9)

Use ping cmd of redis:

import redis
from redis import ConnectionError
import logging

logging.basicConfig()
logger = logging.getLogger('redis')

rs = redis.Redis("localhost")
try:
    rs.ping()
except ConnectionError:
    logger.error("Redis isn't running. try `/etc/init.d/redis-server restart`")
    exit(0)

示例输出:

ERROR:redis:Redis isn't running. try `/etc/init.d/redis-server restart`

答案 1 :(得分:0)

我建议您使用supervision之类的supervisord monit check host redis with address <your_redis_host> if failed icmp type echo count 3 with timeout 3 seconds then alert if failed port 6379 with timeout 15 seconds then alert 来检查进程,主机,文件等是否正在执行此操作; ,如果没有,然后重新启动它。

例如,这里是检查redis的配置:

{{1}}