php实现mysql连接池效果实现代码

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php实现mysql连接池效果实现代码脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

循环从MysqL连接池中@L_360_1@连接,不需要重复创建新的连接。

参考配置修改:可以参考下面的文章

访问量过大,把连接数占满了

<PRe class="brush:PHP;">

/**

  • @author xuleyan
  • @title mysql类
    */

class DbHelper{
//连接池
private $_pools = [];

//连接池大小
const POOLSIZE = 5;

const USERNAME = "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) . "
";
if (count($this->_pools) > 0) {
$one = array_pop($this->_pools);
echo 'getAfter' . count($this->_pools) . "
";
return $one;
} else {
throw new ErrorException ( "数据库连接池中已无链接资源,请稍后重试!" );
}
}

//将用完的数据库链接资源放回到数据库连接池
public function release($conn)
{
echo 'release' . count($this->_pools) . "
";
if (count($this->_pools) >= self::POOLSIZE) {
throw new ErrorException ( "数据库连接池已满!" );
} else {
array_push($this->_pools,$conn);
// $conn = null;
echo 'releaseAfter' . count($this->_pools) . "
";
}
}

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;
}
}
}

脚本宝典总结

以上是脚本宝典为你收集整理的php实现mysql连接池效果实现代码全部内容,希望文章能够帮你解决php实现mysql连接池效果实现代码所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。