首页 > 解决方案 > MySQL:用户有超过 'max_user_connections' 的活动连接

问题描述

我知道这是一个很好的话题,但在我的情况下有点不同。我有一个 SaaS 服务,每个订阅都有自己的数据库。

通过查询SHOW PROCESSLIST我的 25 个数据库,我在每个数据库中都得到了相同的结果:

在此处输入图像描述

所有数据库似乎都没有任何连接,但我仍然收到错误:

用户已经有超过 'max_user_connections' 个活动连接

我正在使用共享主机 CPanel,限制max_connections为 150。

在此处输入图像描述

当显示没有任何查询时,怎么可能max_connections达到?processlist另外,如何在没有主机帮助的情况下重置连接?

这是一个带有 CodeIgniter 框架的 PHP 项目。

标签: phpmysqlcodeigniter

解决方案


解决了

联系主机后,他们将其max_user_connections增加到 20,但问题仍然存在。该项目已经运行了一年多没有问题,所以让我感到困惑。

我使用这个钩子https://github.com/ozanmora/ci_log_query打印所有正在执行的查询,很明显我正在连接到多个未使用的模型。

例如,在我的所有类(和控制器)中,我在构造函数中加载了所有模型,其中一些模型仅用于某个函数,因此它们正在消耗资源而不被使用。

例子:

public function _construct()
{
    $this->load->model('a_model');
    $this->load->model('b_model');
    $this->load->model('c_model');
    $this->load->model('d_model');
    $this->load->model('e_model');
}

而且我只在某些功能中调用它们,例如:

public function test()
{
    $this->a_model->doSometing();
    $this->b_model->doSometing();
}

public function test2()
{
    $this->c_model->doSometing();
}

public function test3()
{
    $this->d_model->doSometing();
}

避免加载不必要的模型/连接的解决方案是仅在需要时加载模型。虽然这在以前没有任何问题,但我最终修复了我所有的控制器/类(这是相当多的)。连接大大减少,现在可以正常工作了。

public function _construct()
{

}

public function test()
{
    $this->load->model('a_model');
    $this->load->model('b_model');
    
    $this->a_model->doSometing();
    $this->b_model->doSometing();
}

public function test2()
{
    $this->load->model('c_model');

    $this->c_model->doSometing();
}

public function test3()
{
    $this->load->model('d_model');

    $this->d_model->doSometing();
}

推荐阅读