
<?php
// 创建数据库连接池配置
$host = '127.0.0.1'; // 数据库服务器地址
$port = '3306'; // 数据库服务器端口
$user = 'root'; // 数据库用户名
$pass = 'password'; // 数据库密码
$database = 'test_db'; // 数据库名
$charset = 'utf8mb4'; // 字符集
$poolSize = 5; // 连接池大小
// 数据库连接池类
class MySQLiConnectionPool {
private $host;
private $port;
private $user;
private $pass;
private $database;
private $charset;
private $pool;
private $availableConnections;
public function __construct($host, $port, $user, $pass, $database, $charset, $poolSize) {
$this>host = $host;
$this>port = $port;
$this>user = $user;
$this>pass = $pass;
$this>database = $database;
$this>charset = $charset;
$this>poolSize = $poolSize;
$this>pool = [];
$this>availableConnections = new SplQueue();
for ($i = 0; $i < $poolSize; $i++) {
$this>availableConnections>enqueue($this>createConnection());
}
}
private function createConnection() {
return new mysqli($this>host, $this>user, $this>pass, $this>database, $this>port, null, $this>charset);
}
public function getConnection() {
if ($this>availableConnections>isEmpty()) {
$connection = $this>createConnection();
$this>pool[] = $connection;
} else {
$connection = $this>availableConnections>dequeue();
}
if ($connection>connect_error) {
$connection>close();
$connection = $this>createConnection();
$this>pool[] = $connection;
}
return $connection;
}
public function releaseConnection($connection) {
if ($connection instanceof mysqli) {
$this>availableConnections>enqueue($connection);
}
}
public function closeAllConnections() {
foreach ($this>pool as $connection) {
$connection>close();
}
}
}
// 使用连接池
$connectionPool = new MySQLiConnectionPool($host, $port, $user, $pass, $database, $charset, $poolSize);
// 获取数据库连接
$connection = $connectionPool>getConnection();
// 执行数据库操作...
// 释放数据库连接
$connectionPool>releaseConnection($connection);
// 关闭所有连接
$connectionPool>closeAllConnections();
?>
代码展示了如何创建一个简单的MySQLi连接池,连接池使用SplQueue来管理可用的连接,并在需要时创建新的连接,当连接不再需要时,它会被释放回连接池,可以通过调用closeAllConnections方法来关闭所有连接。
