作者 zed

优化redis 链接

... ... @@ -33,23 +33,37 @@ class RedisCli
private function exec(callable $fn, string $method)
{
$redis = $this->pool->get();
$redis = $this->pool->get(); // 从池子里取连接
$isHealthy = false; // 标记连接是否健康
try {
return $fn($redis);
$res = $fn($redis); // 执行用户逻辑
$isHealthy = true; // 没报错,认为健康
return $res;
} catch (\RedisException $e) {
$this->logError($method, $e);
// 遇到异常直接销毁该连接,不放回池子
try {
$redis->close(); // 销毁坏连接
$redis->close();
} catch (\Throwable $t) {
}
return false;
} catch (\Throwable $e) {
// 其它错误(比如逻辑 bug),也不要放坏连接回池
$this->logError($method, $e);
try {
$redis->close();
} catch (\Throwable $t) {
}
return false;
} finally {
if ($redis && $redis->isConnected()) {
// 只有当连接执行成功且依然是连接状态时,才放回池子
if ($isHealthy && $redis && $redis->isConnected()) {
$this->pool->put($redis);
}
}
}
// ------------------ 集合 ------------------
public function sAdd($key, $member)
{
... ...