在 PHP 中,使用 MySQLi 連接池可以通過創建一個自定義類來實現。以下是一個簡單的示例,展示了如何實現一個基本的 MySQLi 連接池:
MysqliConnectionPool
的類,用于管理連接池。class MysqliConnectionPool {
private $host = "localhost";
private $user = "username";
private $password = "password";
private $database = "database_name";
private $poolSize = 5;
private $connections = [];
public function __construct($host, $user, $password, $database, $poolSize) {
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->database = $database;
$this->poolSize = $poolSize;
}
public function getConnection() {
if (empty($this->connections)) {
for ($i = 0; $i < $this->poolSize; $i++) {
$this->connections[] = new mysqli($this->host, $this->user, $this->password, $this->database);
if ($this->connections[$i]->connect_error) {
die("Connection failed: " . $this->connections[$i]->connect_error);
}
}
}
$connection = array_pop($this->connections);
return $connection;
}
public function releaseConnection($connection) {
array_push($this->connections, $connection);
}
}
MysqliConnectionPool
類并設置相關參數。$pool = new MysqliConnectionPool("localhost", "username", "password", "database_name", 5);
getConnection()
方法從連接池中獲取一個連接。$connection = $pool->getConnection();
$query = "SELECT * FROM your_table";
$result = $connection->query($query);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}
releaseConnection()
方法將連接放回連接池。$pool->releaseConnection($connection);
這個示例展示了如何創建一個簡單的 MySQLi 連接池。你可以根據需要調整連接池的大小、參數等。請注意,這個示例僅用于演示目的,實際生產環境中可能需要更復雜的錯誤處理和連接管理。