Python - 如何检查Redis服务器是否可用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12857604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - How to check if Redis server is available
提问by Kartik Rokde
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.
我正在开发用于访问 Redis 服务器的 Python 服务(类)。我想知道如何检查 Redis Server 是否正在运行。而且如果不知何故我无法连接到它。
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.
即使我的 Redis 服务器没有运行。
As I found that my Python Code connects to the Server only when I do a set()or get()with my redis instance.
因为我发现我的 Python 代码仅在我对redis 实例执行set()或get()时才连接到服务器。
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??
我想返回正确的消息/错误代码。我怎样才能做到这一点??
采纳答案by Lloyd Moore
The official way to check if redis server availability is ping ( http://redis.io/topics/quickstart).
检查 redis 服务器可用性的官方方法是 ping ( http://redis.io/topics/quickstart)。
One solution is to subclass redis and do 2 things:
一种解决方案是将 redis 子类化并做两件事:
- check for a connection at instantiation
- write an exception handler in the case of no connectivity when making requests
- 在实例化时检查连接
- 在发出请求时在没有连接的情况下编写异常处理程序
回答by Sripathi Krishnan
If you want to test redis connection once at startup, use the ping()command.
如果要在启动时测试一次 redis 连接,请使用该ping()命令。
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.
该命令ping()检查连接,如果无效将引发异常。
- Note - the connection may still fail after you perform the test so this is not going to cover up later timeout exceptions.
- 注意 - 执行测试后连接可能仍会失败,因此这不会掩盖以后的超时异常。
回答by Catalin Luta
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 :
正如您所说,只有当您尝试在服务器上执行命令时,才会建立与 Redis 服务器的连接。如果您不想在不检查服务器是否可用的情况下继续前进,您可以向服务器发送随机查询并检查响应。就像是 :
try:
response = rs.client_list()
except redis.ConnectionError:
#your error handlig code here
回答by Kasapo
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).
这里已经有很好的解决方案,但这是我对 django_redis 的快速和肮脏,它似乎不包含 ping 功能(尽管我使用的是旧版本的 django 并且不能使用最新的 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.
这似乎工作得很好。请注意,如果 redis 正在重新启动并仍在加载在磁盘上保存缓存条目的 .rdb 文件,那么它会抛出 BusyLoadingError,尽管它的基类是 ConnectionError 因此可以捕获它。
You can also simply except on redis.exceptions.RedisErrorwhich is the base class of all redis exceptions.
您也可以简单地在redis.exceptions.RedisErrorwhich 是所有 redis 异常的基类。
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).
根据您的需要,另一种选择是创建 get 和 set 函数,以在设置/获取值时捕获 ConnectionError 异常。然后你可以继续或等待或任何你需要做的事情(引发一个新的异常或只是抛出一个更有用的错误消息)。
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.
如果您绝对依赖于设置/获取缓存值(就我而言,如果缓存处于脱机状态,因为我们通常必须“继续”),则这可能无法正常工作,在这种情况下,有例外并让程序/脚本死亡并使 redis 服务器/服务恢复到可访问状态。
回答by Yogesh Yadav
Use ping()
使用 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

