当前位置:Gxlcms > 数据库问题 > Mysql连接池

Mysql连接池

时间:2021-07-01 10:21:17 帮助过:26人阅读

show processlist;

PHP代码的编写

<?php
/**
* 数据库连接池
*/
class Pool {
// 可用的db对象数量
private $_avaNum = 2;
// db对象的总数
private $_total = 2;
// db对象的列表
private $_dbs = [];
// 连接数据信息
private $_dsn = ‘mysql:host=localhost;dbname=test;charset=utf8‘;
// 用户名
private $_user = ‘root‘;
// 密码
private $_pass = ‘admin888‘;
// 类对象
private static $_ins = null;
private function __construct() {
$this->_connection();
}
// 连接数据库
private function _connection() {
for ($i = 0; $i < $this->_total; $i++) {
$this->_dbs[] = new PDO($this->_dsn, $this->_user, $this->_pass);
}
}
// 初始化
public static function getIns() {
if (is_null(self::$_ins)) {
self::$_ins = new self();
}
return self::$_ins;
}
/**
* 查询
* @param string $sql
*/
public function findAll(string $sql) {
if ($this->_avaNum <= 0)
throw new Exception(‘没有可用的连接数‘);
// 池中取db对象
$this->_avaNum--;
$pdo = array_pop($this->_dbs);
$row = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
// db放入池中
$this->_avaNum++;
array_unshift($this->_dbs, $pdo);
return $row;
}
}
// 创建一个httpserver对象
$http = new swoole_http_server(‘0.0.0.0‘, 6060);
// 设置worker进程数量
$http->set(
[
# 进程数量
‘worker_num‘ => 1,
# worker进程最大的处理数量,达到将会销毁
‘max_request‘ => 1000,
# task数量
#‘task_worker_num‘ => 10
]
);
// worker进程启动的时候启动
3、效果
命令行执行脚本
浏览器中查看
$http->on(
‘WorkerStart‘, function (swoole_server $server, int $worker_id) use ($obj) {
$GLOBALS[‘obj‘] = Pool::getIns();
}
);
// 请求事件
$http->on(
‘request‘, function (swoole_http_request $request, swoole_http_response $response) use
($http) {
$row = $GLOBALS[‘obj‘]->findAll("select * from tt_article");
$html = json_encode($row, JSON_UNESCAPED_UNICODE);
$response->header(‘server‘, ‘wuchen‘);
$response->header(‘Content-Type‘, ‘application/json;charset=utf-8‘);
$response->end($html);
}
);
// 启动服务
$http->start();

命令行执行脚本

mysql中查看

技术图片

 

Mysql连接池

标签:response   localhost   charset   slist   服务   strong   RKE   app   art   

人气教程排行