如何判断 redis 连接是否有效

2025-04-28 05:38:41
推荐回答(4个)
回答1:

调用redis客户端的ping方法。如果返回pong,则连接有效。如果抛出异常表示连接有问题。

回答2:

>>> conn = redis.StrictRedis('1.2.3.4', 1234, socket_timeout=3)
>>> conn.get('xxxxxxxxxxxxx')
......
redis.exceptions.ConnectionError: Error connecting to 1.2.3.4:1234. timed out.

回答3:

只能靠超时来判断。
参考代码

var redispool = poolModule.Pool({
name : 'redis',
create : function(callback) {

var client = Redis.createClient(configs.dbconfig.dbredis.port,
configs.dbconfig.dbredis.host);
// client.connect();
callback(null, client);
},
destroy : function(client) { client.quit(); },
max : 10,
// optional. if you set this, make sure to drain() (see step 3)
min : 2,
// specifies how long a resource can stay idle in pool before being removed
idleTimeoutMillis : 30000
// if true, logs via console.log - can also be a function
//log : true
});
function getRedisClient() {
return redispool.acquireAsync().disposer(function(client, promise) {
console.log("redispool.release(client)")
redispool.release(client);
});
}
dbs.redisclient = getRedisClient ;
--------------
检测redisclient是否为空

回答4:

//第一步:实例化redis对象
$redis = new redis();
//第二步:php客户端设置的ip及端口
$redis->connect("127.0.0.1","6379");
//第三部:配置连接密码 检测redis服务器连接状态

//连接失败直接结束 并输出
$auth = $redis->auth('zhenai') or die("redis 服务器连接失败");
// var_dump($auth);连接成功 返回 true 反之 返回false

//第四步 可用可不用
echo $connect_status=$redis->ping();
if($connect_status==="+PONG")
{
echo "redis 服务器连接成功";
}
//就是如此简单