
mysql连接池在数据库重启后失效的解决方法
在swooledistributed 3中,如果使用官方提供的mysql连接池,数据库重启后,所有连接可能失效。导致这个问题的原因可能是由于底层重连逻辑存在问题。
以下是解决方法:
$result = $client->connect($set);
if (!$result) {
// 创建新的客户端并重试连接
$client = new swoole\coroutine\mysql();
$result = $client->connect($set);
}通过此修改,如果重连失败,程序会创建一个新的客户端并重新尝试连接。
确保重连时将setdefer值设置为false,因为事务不允许设置此值。
$client->setdefer(false);
示例代码:
/**
* @param $sql
* @param null $client
* @param MySqlCoroutine $mysqlCoroutine
* @return mixed
* @throws \Throwable
*/
public function query($sql, $client = null, MySqlCoroutine $mysqlCoroutine)
{
$notPush = false;
$delayRecv = $mysqlCoroutine->getDelayRecv();
if ($client == null) {
$client = $this->pool_chan->pop();
$client->setDefer($delayRecv);
} else {//这里代表是事务
$notPush = true;
//事务不允许setDefer
$delayRecv = false;
$client->setDefer($delayRecv);
}
if (!$client->connected) {
$set = $this->config['mysql'][$this->active];
$result = $client->connect($set);
if (!$result) {
// 创建新的客户端并重试连接
$client = new Swoole\Coroutine\MySQL();
$result = $client->connect($set);
if (!$result) {
$this->pushToPool($client);
$errcode = $client->errno ?? '';
$mysqlCoroutine->getResult(new SwooleException(sprintf("err:%s,code:%s", $client->connect_error, $errcode))); //在这里报的错
}
}
}
// ...
}以上就是SwooleDistributed 3中,MySQL连接池如何解决数据库重启后连接失效的问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号