在 PHP 中,使用 MySQL 连接池可以通过第三方库或者 PHP 扩展来实现。这里我将为您介绍两种方法:使用 PHP 扩展 mysqli 和使用第三方库 Amphp/MySQL。
方法一:使用 PHP 扩展 mysqli
首先,确保您的 PHP 安装包含了 mysqli 扩展。您可以通过运行 php -m | grep mysqli 命令来检查。如果没有安装,请参考 PHP 官方文档来安装 mysqli 扩展。
创建一个名为 mysqli_pool.php 的文件,并添加以下代码:
<?php
class MysqliPool {
private $pool = [];
private $host;
private $user;
private $password;
private $database;
private $port;
private $socket;
private $charset;
public function __construct($config) {
$this->host = $config['host'];
$this->user = $config['user'];
$this->password = $config['password'];
$this->database = $config['database'];
$this->port = $config['port'] ?? 3306;
$this->socket = $config['socket'];
$this->charset = $config['charset'] ?? 'utf8mb4';
}
public function getConnection() {
if (empty($this->pool)) {
$this->pool[] = $this->createConnection();
}
return array_shift($this->pool);
}
public function releaseConnection($conn) {
$this->pool[] = $conn;
}
private function createConnection() {
$mysqli = new mysqli();
$mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 1);
$mysqli->options(MYSQLI_OPT_SSL_VERIFY_SERVER_CERT, false);
$mysqli->options(MYSQLI_OPT_RECONNECT, true);
$mysqli->real_connect($this->host, $this->user, $this->password, $this->database, $this->port, $this->socket, MYSQLI_CLIENT_MULTISUBMIT);
if ($mysqli->connect_error) {
throw new Exception('MySQL connection error: ' . $mysqli->connect_error);
}
$mysqli->set_charset($this->charset);
return $mysqli;
}
}
<?php
require_once 'mysqli_pool.php';
$config = [
'host' => 'localhost',
'user' => 'your_username',
'password' => 'your_password',
'database' => 'your_database'
];
$pool = new MysqliPool($config);
$conn = $pool->getConnection();
// 使用连接进行数据库操作
$result = $conn->query('SELECT * FROM your_table');
// ...
// 释放连接
$pool->releaseConnection($conn);
方法二:使用第三方库 Amphp/MySQL
composer require amphp/mysql
mysql_pool.php 的文件,并添加以下代码:<?php
require_once 'vendor/autoload.php';
use Amp\Loop;
use Amp\MySQL\Connection;
use Amp\MySQL\Pool;
$loop = Loop::create();
$config = [
'host' => 'localhost',
'port' => '3306',
'user' => 'your_username',
'password' => 'your_password',
'database' => 'your_database',
'charset' => 'utf8mb4'
];
$pool = new Pool(
function () use ($config) {
$connection = new Connection($config);
await $connection->connect();
return $connection;
},
10 // 连接池大小
);
// 使用连接进行数据库操作
$future = $pool->query('SELECT * FROM your_table');
$pool->on('complete', function (\Throwable $e) use ($loop) {
Loop::stop();
});
$loop->run();
$result = $future->wait();
// 处理结果
// ...
// 关闭连接池
$pool->close();
这两种方法都可以实现 PHP 的 MySQL 连接池。您可以根据自己的需求选择合适的方法。