PHP如何實作資料庫連線池
先定義一個類別並宣告一個屬性為連結池子;然後在建構方法中向池子進行填充連接實例;最後再定義一個取出方法和放回方法,取出時將連接池最後一個連接實例進行出棧並返回,放回時將連接實例壓入連接池末棧即可。
實例程式碼:
<?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); } } }
推薦教學:《PHP教學》
以上是PHP如何實作資料庫連線池的詳細內容。更多資訊請關注PHP中文網其他相關文章!