外链论坛

 找回密码
 立即注册
搜索
查看: 12|回复: 0

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

[复制链接]

1299

主题

6

回帖

9910万

积分

论坛元老

Rank: 8Rank: 8

积分
99105760
发表于 2024-7-10 17:50:53 | 显示全部楼层 |阅读模式

循环从mysql连接池中获取连接,不必须重复创建新的连接。

参考配置修改:能够参考下面的文案

防止拜访量过大,把连接数占满了

<?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:B;

$username = self::USERNAME;

$password = self:ASSWORD;

$host = self::HOST;

//持久化连接

$presistent = array(PDO::ATTR_PERSISTENT => true);

for ($i=0; $i < self:OOLSIZE; $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:OOLSIZE) {

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;

}

}

}

另一的文件这般调用

<?php

require_once db.php;

$sql = select * from user;

$dbhelper = new DbHelper;

f

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|外链论坛 ( 非经营性网站 )|网站地图

GMT+8, 2024-7-29 11:22 , Processed in 0.158582 second(s), 22 queries .

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.