Python – How to check if Redis server is available

Question:

I’m developing a Python Service(Class) for accessing Redis Server. I want to know how to check if Redis Server is running or not. And also if somehow I’m not able to connect to it.

Here is a part of my code

import redis
rs = redis.Redis("localhost")
print rs

It prints the following

<redis.client.Redis object at 0x120ba50>

even if my Redis Server is not running.

As I found that my Python Code connects to the Server only when I do a set() or get() with my redis instance.

So I dont want other services using my class to get an Exception saying

redis.exceptions.ConnectionError: Error 111 connecting localhost:6379. Connection refused.

I want to return proper message/Error code. How can I do that??

Asked By: Kartik Rokde

||

Answers:

If you want to test redis connection once at startup, use the ping() command.

from redis import Redis

redis_host = '127.0.0.1'
r = Redis(redis_host, socket_connect_timeout=1) # short timeout for the test

r.ping() 

print('connected to redis "{}"'.format(redis_host)) 

The command ping() checks the connection and if invalid will raise an exception.

  • Note – the connection may still fail after you perform the test so this is not going to cover up later timeout exceptions.
Answered By: Sripathi Krishnan

As you said, the connection to the Redis Server is only established when you try to execute a command on the server. If you do not want to go head forward without checking that the server is available, you can just send a random query to the server and check the response. Something like :

try:
    response = rs.client_list()
except redis.ConnectionError:
    #your error handlig code here    
Answered By: Catalin Luta

The official way to check if redis server availability is ping ( http://redis.io/topics/quickstart ).

One solution is to subclass redis and do 2 things:

  1. check for a connection at instantiation
  2. write an exception handler in the case of no connectivity when making requests
Answered By: Lloyd Moore

There are already good solutions here, but here’s my quick and dirty for django_redis which doesn’t seem to include a ping function (though I’m using an older version of django and can’t use the newest django_redis).

# assuming rs is your redis connection
def is_redis_available():
    # ... get redis connection here, or pass it in. up to you.
    try:
        rs.get(None)  # getting None returns None or throws an exception
    except (redis.exceptions.ConnectionError, 
            redis.exceptions.BusyLoadingError):
        return False
    return True

This seems to work just fine. Note that if redis is restarting and still loading the .rdb file that holds the cache entries on disk, then it will throw the BusyLoadingError, though it’s base class is ConnectionError so it’s fine to just catch that.

You can also simply except on redis.exceptions.RedisError which is the base class of all redis exceptions.

Another option, depending on your needs, is to create get and set functions that catch the ConnectionError exceptions when setting/getting values. Then you can continue or wait or whatever you need to do (raise a new exception or just throw out a more useful error message).

This might not work well if you absolutely depend on setting/getting the cache values (for my purposes, if cache is offline for whatever we generally have to “keep going”) in which case it might make sense to have the exceptions and let the program/script die and get the redis server/service back to a reachable state.

Answered By: Kasapo

Use ping()

from redis import Redis

conn_pool = Redis(redis_host)
# Connection=Redis<ConnectionPool<Connection<host=localhost,port=6379,db=0>>>

try:
    conn_pool.ping()
    print('Successfully connected to redis')
except redis.exceptions.ConnectionError as r_con_error:
    print('Redis connection error')
    # handle exception
Answered By: Yogesh Yadav

I have also come across a ConnectionRefusedError from the sockets library, when redis was not running, therefore I had to add that to the availability check.

r = redis.Redis(host='localhost',port=6379,db=0)

def is_redis_available(r):
    try:
        r.ping()
        print("Successfully connected to redis")
    except (redis.exceptions.ConnectionError, ConnectionRefusedError):
        print("Redis connection error!")
        return False
    return True

if is_redis_available(r):
    print("Yay!")
Answered By: hexerei software

Redis server connection can be checked by executing ping command to the server.

>>> import redis
>>> r = redis.Redis(host="127.0.0.1", port="6379")
>>> r.ping()
True

using the ping method, we can handle reconnection etc. For knowing the reason for error in connecting, exception handling can be used as suggested in other answers.

try:
    is_connected = r.ping()
except redis.ConnectionError:
    # handle error
Answered By: Akash Ranjan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.