PHP Redis连接无法关闭,刷新后连接数持续上涨求助
问题
尝试关闭Redis连接但无效,每次刷新页面时活跃连接数都会增加。使用MAMP Pro监控Redis实时状态,刷新页面时活跃连接数持续上涨,连接并未真正关闭。
代码如下:
$this->type = $this->api->settings['cache']['type']; if ( $this->type == "Redis" ) { $this->redis = new Redis(); $this->redis->connect( $this->api->settings['cache']['server'] , $this->api->settings['cache']['port'] , 0); $this->api->logs->log( array("CACHE" => $this->type, "Connected" => true , "ping" => $this->redis->ping()) ); $this->redis->close(); $this->redis = null; }
解决方案
- 改用
quit()替代close():Redis扩展中quit()会向服务器发送退出命令,触发服务器主动关闭连接,比close()的底层连接释放逻辑更可靠。替换代码中的$this->redis->close();为$this->redis->quit();再测试。 - 添加异常捕获确保关闭逻辑执行:如果
ping()或连接过程抛出异常,后续的关闭代码会被跳过。用try-catch-finally包裹操作,保证无论是否出错都执行连接清理:if ( $this->type == "Redis" ) { $this->redis = new Redis(); try { $this->redis->connect( $this->api->settings['cache']['server'] , $this->api->settings['cache']['port'] , 0); $this->api->logs->log( array("CACHE" => $this->type, "Connected" => true , "ping" => $this->redis->ping()) ); } catch (Exception $e) { $this->api->logs->log( array("CACHE_ERROR" => $e->getMessage()) ); } finally { if ($this->redis) { $this->redis->quit(); $this->redis = null; } } } - 检查Redis服务器超时配置:查看Redis配置文件中的
timeout参数,若设置为0表示永不超时,未正确关闭的连接会长期留存。建议设置合理的闲置超时时间(如300秒),让服务器主动清理无效连接。 - 验证真实连接数:通过
redis-cli info clients命令直接查看Redis服务器的实时连接数据,对比MAMP Pro的监控结果,排除监控工具统计延迟或逻辑误差的可能。 - 确认是否启用持久化连接:部分环境下PHP Redis扩展会默认启用持久化连接,
connect()可能实际创建了持久连接,此时close()不会真正断开。可以在connect()时显式禁用持久化,或改用pconnect()配合quit()处理。
内容的提问来源于stack exchange,提问作者Kodr.F
相关产品推荐
相关产品推荐

