简单 PHP 数据库连接池类设计:

      class DatabaseConnectionPool {

    private $host;
    private $username;
    private $password;
    private $database;
    private $maxConnections;
    private $connectionPool = [];
    private $usedConnections = [];

    public function __construct($host, $username, $password, $database, $maxConnections = 10) {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
        $this->database = $database;
        $this->maxConnections = $maxConnections;

        $this->initialize(); // 初始化连接池
    }

    // 初始化连接池
    private function initialize() {
        for ($i = 0; $i < $this->maxConnections; $i++) {
            $this->connectionPool[] = $this->createConnection();
        }
    }

    // 创建新的数据库连接
    private function createConnection() {
        $connection = new mysqli($this->host, $this->username, $this->password, $this->database);
        if ($connection->connect_error) {
            throw new Exception("Connection failed: " . $connection->connect_error);
        }
        return $connection;
    }

    // 从连接池获取连接
    public function getConnection() {
        if (!empty($this->connectionPool)) {
            $connection = array_pop($this->connectionPool);
            $this->usedConnections[] = $connection;
            return $connection;
        } else {
            // 连接池已满,可以等待或抛出异常
            throw new Exception("Connection pool is full."); 
        }
    }

    // 释放连接,将其放回连接池
    public function releaseConnection($connection) {
        $key = array_search($connection, $this->usedConnections);
        if ($key !== false) {
            unset($this->usedConnections[$key]);
            $this->connectionPool[] = $connection;
        }
    }

    // 销毁连接池,关闭所有连接
    public function __destruct() {
        foreach (array_merge($this->connectionPool, $this->usedConnections) as $connection) {
            $connection->close();
        }
    }
}
    

使用方法:

      // 创建连接池对象
$pool = new DatabaseConnectionPool("localhost", "user", "password", "database", 10);

// 获取连接
$connection = $pool->getConnection();

// 执行数据库操作...

// 释放连接
$pool->releaseConnection($connection);
    

说明:

  • 该连接池类维护两个数组:
    • $connectionPool:存储空闲的数据库连接。
    • $usedConnections:存储正在使用的数据库连接。
  • getConnection() 方法会从 $connectionPool 中获取一个连接,如果 $connectionPool 为空,则抛出异常。
  • releaseConnection() 方法将连接放回 $connectionPool 中,以便其他请求可以使用。
  • __destruct() 方法在对象销毁时关闭所有连接,释放资源。

注意:

  • 这只是一个简单的示例,实际应用中可能需要根据具体需求进行扩展和优化。
  • 例如,可以添加连接池监控、连接超时处理、连接错误处理等功能。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注