PHP如何實(shí)現(xiàn)數(shù)據(jù)庫連接池
首先定義一個(gè)類并聲明一個(gè)屬性作為連接池子;然后在構(gòu)造方法中向池子進(jìn)行填充連接實(shí)例;最后再定義一個(gè)取出方法和放回方法,取出時(shí)將連接池最后一個(gè)連接實(shí)例進(jìn)行出棧并返回,放回時(shí)將連接實(shí)例壓入連接池末棧即可。
實(shí)例代碼:
<?php namespace DbConnect; 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( "數(shù)據(jù)庫連接池中已無鏈接資源,請(qǐng)稍后重試!" ); } else { return array_pop($this->connects); } } public function release($connect) { if (count($this->connects) >= $this->size) { throw new ErrorException("數(shù)據(jù)庫連接池已滿"); } else { array_push($this->connects, $connect); } } }
推薦教程:《PHP教程》