下面是为Pear DB实现数据库连接池的正确方法


Is the following the right way to implement database connection pool for Pear DB?

我知道PHP中没有连接池,我们目前使用的是Pear DB。

我有一个遗留的cron作业代码,它使用梨数据库连接。

while (true) {
    ...
    foreach ($keys as $key) {
        $connection_string = get_connection_string_based_on_key($key);
        $DB = & 'DB::connect($connection_string);
        ...
        // Avoid resource leakage.
        $DB->disconnect();
    }
}

我们意识到DB::connect确实给了我们一些性能热点。我计划创建一个伪连接池

$pool = array();
while (true) {
    ...
    foreach ($keys as $key) {
        $connection_string = get_connection_string_based_on_key($key);
        if (array_key_exists ($connection_string, $pool) {
            $DB = $pool[$connection_string];
        } else {
            $DB = & 'DB::connect($connection_string);
            $pool[$connection_string] = $DB;
        }
        ...
        // No $DB->disconnect(); As we want the 
        // DB connection remains valid inside the pool.
    }
}

cron作业可能会运行几天、几周或几个月。我想知道,这样的伪连接池背后有什么猫猫吗?例如,

  1. 将DB连接保持有效,它停留在池内很长一段时间后(说一个星期)?
  2. 数据库资源可能用完?如果是,什么是合适的机制来处理不断增长的池?

这不是关于PHP代码的问题。连接超时时间和最大同时连接数必须在数据库系统中配置。

使用mysql时:

连接:http://www.electrictoolbox.com/update-max-connections-mysql/

超时:通过python连接时,如何更改默认Mysql连接超时时间?

我认为connect_timeout=0意味着mysql数据库将尽可能长时间保持连接打开。据我所知,没有无限制连接的配置选项(关于系统资源)。