一 .什麼是mysql連接配接池
場景:每秒同時有1000個并發,但是這個mysql同時隻能處理400個連接配接,mysql會當機。
解決方案:連接配接池,這個連接配接池建立了200個和mysql的連接配接,這1000個并發就有順序的共享這連接配接池中的200個連接配接。
這個連接配接池能夠帶來額外的性能提升,因為這個和mysql建立連接配接的這個過程消耗較大,使用連接配接池隻需連接配接一次mysql。
連接配接池定義:永不斷開,要求我們的這個程式是一個常駐記憶體的程式。資料庫連接配接池(Connection pooling)是程式啟
動時建立足夠的資料庫連接配接,并将這些連接配接組成一個連接配接池,由程式動态地對池中的連接配接進行申請,使用,釋放。
二.小案例
查找使用者表資料庫最新注冊的3個會員?
(1)小提示
show processlist #mysql檢視連接配接數
(2)建立10個mysql連接配接示例代碼
<?php
/**
* Created by PhpStorm.
* User: Luke
* Date: 2019/10/30
* Time: 14:12
*/
//編寫mysql連接配接池,這個類隻能被執行個體化一次(單例)
class MysqlConnectionPool
{
private static $instance;//單例對象
private $connection_num = 10;//連接配接數量
private $connection_obj = [];
//構造方法連接配接mysql,建立20mysql連接配接
private function __construct()
{
for($i=0;$i<$this->connection_num;$i++){
$dsn = "mysql:host=127.0.0.1;dbnane=swoole";
$this->connection_obj[] = new Pdo($dsn,'root','rootmysql123');
}
}
private function __clone()
// TODO: Implement __clone() method.
public static function getInstance()
if(is_null(self::$instance)){
self::$instance = new self();
}
MysqlConnectionPool::getInstance();
//建立swool的http伺服器對象
$serv = new swoole_http_server('0.0.0.0',8000);
//當浏覽器連結點這個http伺服器的時候,向浏覽器發送helloworld
$serv->on('request', function($request,$response){
//$request包含這個請求的所有資訊,比如參數
//$response包含傳回給浏覽器的所有資訊,比如helloworld
//(2.3)向浏覽器發送helloworld
$response->end("hello world");
});
//啟動http伺服器
$serv->start();
(3)效果

(4)完善mysql連接配接池
private $connection_num = 20;//連接配接數量
private $avil_connection_num = 20;//可用連接配接
$dsn = "mysql:host=127.0.0.1;dbname=swoole";
return self::$instance;
//執行sql操作
public function query($sql)
if($this->avil_connection_num==0){
throw new Exception("暫時沒有可用的連接配接诶,請稍後");
//執行sql語句
$pdo = array_pop($this->connection_obj);
//可用連接配接數減1
$this->avil_connection_num --;
//使用從連接配接池中取出的mysql連接配接執行查詢,并且把資料取成關聯數組
$rows = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
//把mysql連接配接放回連接配接池,可用連接配接數+1
array_push($this->connection_obj,$pdo);
$this->avil_connection_num ++;
return $rows;
//向浏覽器發送helloworld
$stop = false;
while (!$stop){
try{
$sql = "SELECT * FROM user ORDER BY id DESC LIMIT 5";
$rows = MysqlConnectionPool::getInstance()->query($sql);
$response->end(json_encode($rows));
$stop = true;
}catch (Exception $e){
usleep(100000);
有需要交流的小夥伴可以點選這裡加本人QQ:luke
最好的貴人
就是拼命努力的自己。