yii2 Console 中 Swoole 多进程 Mysql超时解决方法
在yii2的console执行的 swoole php脚本,该脚本一直在后台执行.
执行一晚上后发现其他客户端无法连接tcp服务 发现输出此报错信息
SQLSTATE[HY000]: General error: 2006 MySQL server has gone away
The SQL being executed was:
首先,我们来看一下yii2中 open方法的实现:
/**
* Establishes a DB connection.
* It does nothing if a DB connection has already been established.
* @throws Exception if connection fails
*/ public function open()
{
if ($this->pdo !== null) {
return;
}
他这里只判断pdo属性是否不等于null,此操作无法判断连接是否已被主动关闭
操作方案
进程启动记录db连接时间
tcp服务接收一条数据时 先判断连接时间是否超出1分钟 超出断开
使用\Yii::$app->db->close()来关闭数据库连接。
然后下面的mysql操作他会自动打开连接
至此解决问题
代码如下
$server->on('workerstart', function ($server, $fd) {
//>> 记录连接数据库时间
$server->connect_db_time = time();
});
function onReceive($serv, $fd, $tid, $data)
{
// 判断运行时间是否超过1分钟
if($serv->connect_db_time < time() - 60){
$this->log('Close Db');
$serv->connect_db_time = time();
// 记录新的连接时间
\Yii::$app->getDb()->close();
// 关闭数据库连接
FuncHelper::getRedis()->close();
// 此处关闭redis连接
}
}
注:mysql wait_timeout 通常默认值为 28800 8小时断开 修改wait_timeout长时间通常不建议