Python - 如何检查Redis服务器是否可用 [英] Python - How to check if Redis server is available

查看:33
本文介绍了Python - 如何检查Redis服务器是否可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发用于访问 Redis 服务器的 Python 服务(类).我想知道如何检查 Redis Server 是否正在运行.还有如果我无法连接到它.

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.

这是我的代码的一部分

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

打印以下内容

<redis.client.Redis object at 0x120ba50>

即使我的 Redis 服务器没有运行.

even if my Redis Server is not running.

因为我发现我的 Python 代码仅在我对 redis 实例执行 set()get() 时才连接到服务器.

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

推荐答案

官方检查 redis 服务器是否可用的方法是 ping ( http://redis.io/topics/quickstart ).

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

一种解决方案是将 redis 子类化并做两件事:

One solution is to subclass redis and do 2 things:

  1. 在实例化时检查连接
  2. 在发出请求时没有连接的情况下编写异常处理程序

这篇关于Python - 如何检查Redis服务器是否可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆