How does PHP implement a database connection pool?
First define a class and declare an attribute as a connection pool; then add data to the pool in the constructor Fill in the connection instance; finally define a take-out method and a put-back method. When taking out, the last connection instance of the connection pool will be popped out of the stack and returned. When put back, the connection instance will be pushed into the last stack of the connection pool.
Example code:
<?php namespace Db\Connect; class Pool { protected $size = 10; protected $connects = []; protected $dbConf = [ 'hostname' => '127.0.0.1', 'username' => 'root', 'password' => '123456', 'dbname' => 'dbname' ]; public function __construct($size = 10, $dbConf = []) { $this->size = $size; $this->dbdbConf = array_merge($this->dbdbConf, $dbdbConf); for($index = 1; $index <= $this->size; $index ++) { $connect = mysqli_connect( $this->dbConf['hostname'], $this->dbConf['username'], $this->dbConf['password'], $this->dbConf['dbname'] ); array_push($this->connects, $connect); } } public function getConnect() { if (count($this->connects) <= 0) { throw new \ErrorException( "数据库连接池中已无链接资源,请稍后重试!" ); } else { return array_pop($this->connects); } } public function release($connect) { if (count($this->connects) >= $this->size) { throw new \ErrorException("数据库连接池已满"); } else { array_push($this->connects, $connect); } } }
Recommended tutorial: "PHP Tutorial"
The above is the detailed content of How to implement database connection pool in PHP. For more information, please follow other related articles on the PHP Chinese website!