作者 zed

优化redis 链接

@@ -33,23 +33,37 @@ class RedisCli @@ -33,23 +33,37 @@ class RedisCli
33 33
34 private function exec(callable $fn, string $method) 34 private function exec(callable $fn, string $method)
35 { 35 {
36 - $redis = $this->pool->get(); 36 + $redis = $this->pool->get(); // 从池子里取连接
  37 + $isHealthy = false; // 标记连接是否健康
37 try { 38 try {
38 - return $fn($redis); 39 + $res = $fn($redis); // 执行用户逻辑
  40 + $isHealthy = true; // 没报错,认为健康
  41 + return $res;
39 } catch (\RedisException $e) { 42 } catch (\RedisException $e) {
40 $this->logError($method, $e); 43 $this->logError($method, $e);
  44 + // 遇到异常直接销毁该连接,不放回池子
41 try { 45 try {
42 - $redis->close(); // 销毁坏连接 46 + $redis->close();
  47 + } catch (\Throwable $t) {
  48 + }
  49 + return false;
  50 + } catch (\Throwable $e) {
  51 + // 其它错误(比如逻辑 bug),也不要放坏连接回池
  52 + $this->logError($method, $e);
  53 + try {
  54 + $redis->close();
43 } catch (\Throwable $t) { 55 } catch (\Throwable $t) {
44 } 56 }
45 return false; 57 return false;
46 } finally { 58 } finally {
47 - if ($redis && $redis->isConnected()) { 59 + // 只有当连接执行成功且依然是连接状态时,才放回池子
  60 + if ($isHealthy && $redis && $redis->isConnected()) {
48 $this->pool->put($redis); 61 $this->pool->put($redis);
49 } 62 }
50 } 63 }
51 } 64 }
52 65
  66 +
53 // ------------------ 集合 ------------------ 67 // ------------------ 集合 ------------------
54 public function sAdd($key, $member) 68 public function sAdd($key, $member)
55 { 69 {