Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to check if Redis server is available

Tags:

python

redis

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??

like image 721
Kartik Rokde Avatar asked Oct 12 '12 10:10

Kartik Rokde


People also ask

How do I know if Redis is available?

you can do it by this way. $redis = new Redis(); $redis->connect('127.0. 0.1', 6379); echo $redis->ping(); and then check if it print +PONG , which show redis-server is running.

How do I know if Redis server is running?

To start Redis client, open the terminal and type the command redis-cli. This will connect to your local server and now you can run any command. In the above example, we connect to Redis server running on the local machine and execute a command PING, that checks whether the server is running or not.


2 Answers

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
like image 154
Lloyd Moore Avatar answered Oct 09 '22 21:10

Lloyd Moore


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.
like image 35
Sripathi Krishnan Avatar answered Oct 09 '22 23:10

Sripathi Krishnan