php实现mysql连接池效果实现代码
循环从mysql连接池中获取连接,不需要重复创建新的连接。
参考配置修改:可以参考下面的文章
防止访问量过大,把连接数占满了
<"root";
const PASSWORD = "root";
const HOST = "127.0.0.1";
const DB = "test";
public function __construct()
{
$db = self::DB;
$username = self::USERNAME;
$password = self::PASSWORD;
$host = self::HOST;
//持久化连接
$presistent = array(PDO::ATTR_PERSISTENT => true);
for ($i=0; $i < self::POOLSIZE; $i++) {
$connection = new PDO("mysql:dbname=$db;host=$host", $username, $password);
// sleep(3);
array_push($this->_pools, $connection);
}
}
//从数据库连接池中获取一个数据库链接资源
public function getConnection()
{
echo 'get' . count($this->_pools) . "<br>";
if (count($this->_pools) > 0) {
$one = array_pop($this->_pools);
echo 'getAfter' . count($this->_pools) . "<br>";
return $one;
} else {
throw new ErrorException ( "<mark>数据库连接池中已无链接资源,请稍后重试!</mark>" );
}
}
//将用完的数据库链接资源放回到数据库连接池
public function release($conn)
{
echo 'release' . count($this->_pools) . "<br>";
if (count($this->_pools) >= self::POOLSIZE) {
throw new ErrorException ( "<mark>数据库连接池已满!</mark>" );
} else {
array_push($this->_pools, $conn);
// $conn = null;
echo 'releaseAfter' . count($this->_pools) . "<br>";
}
}
public function query($sql)
{
try {
$conn = $this->getConnection();
$res = $conn->query($sql);
$this->release($conn);
return $res;
} catch (ErrorException $e) {
print 'error:' . $e->getMessage();
die;
}
}
public function queryAll($sql)
{
try {
$conn = $this->getConnection();
$sth = $conn->prepare($sql);
$sth->execute();
$result = $sth->fetchAll();
return $result;
} catch (PDOException $e) {
print 'error:' . $e->getMessage();
die;
}
}
}
在另外的文件这样调用
<"htmlcode">class BaseMysql extends Model { protected $connection = array( 'db_type' => 'mysql', 'db_user' => '***', 'db_pwd' => '*******', 'db_host' => '*******', 'db_port' => '3306', 'db_name' => 'custom', 'db_params' => array('persist' => true), ); }如果你认为,配置这个就万事大吉了,那就大错特错了。
2 mysql -> my.cnf修改配置:
[mysqld]interactive_timeout =60 // 交互连接(mysql-client)的过期时间。
wait_timeout =30 // 长连接的过期时间时间。 这个一定要改啊!默认是8个小时。 如果请求量大点,很快连接数就占满了。
max_connections = 100 //最大连接数,可以认为是连接池的大小3 php.ini 修改:
[MySql]
mysql.allow_persistent = On
mysql.max_persistent = 99 // 要小于mysql配置的最大连接数
mysql.max_links = 994 webserver如果是apache ,需要启用keep-alive。 否则,一旦请求退出,长连接将无法再重用。
webserver 是nginx的情况:
pm = dynamic // 默认启动一些子进程,用于处理http请求。
pm.max_children // 最大的子进程数。 这个配置要小于 mysql 的max_connections。5 如果发现还是不能用,请检查操作系统的keepalive 是否启用。
综述:
需要 keep-alive 和 数据库长连接同时启用,否则长连接回白白的占用mysql的连接数资源,而无法重用。
对于 nginx + php-fpm 的情况,其实是保持了 php-fpm 子进程与mysql的长连接。 前端的http请求被分配给哪个 php-fpm子进程,该子进程就重用自己与mysql 的长连接。上述是一整天的研究结果,不完备的地方,请大家指出,在此先行谢过!
下一篇:php使用imagecopymerge()函数创建半透明水印