How do I check if redis is running before I start

2019-05-14 21:52发布

问题:

I am new to Flask and want to make sure the redis server is running and start it if it isn't. Here's what I have:

@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)

However, I get an error "OSError: [Errno 2] No such file or directory"

Is there an easier way to check if the redis server is running?

回答1:

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)

Sample Output:

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


回答2:

I would suggest you to use some kind of a supervision like supervisord or monit they are designed to check if process, host, file and so on is doing it;s job, and if not,then restart it.

For example here is the config to check redis:

 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