如何在 Swoole 中优雅的实现 MySQL 连接池
如何在 Swoole 中优雅的实现 MySQL 连接池
一、为什么需要连接池 ?
数据库连接池指的是程序和数据库之间保持一定数量的连接不断开,
并且各个请求的连接可以相互复用,
减少重复连接数据库带来的资源消耗,
一定程度上提高了程序的并发性能。
二、连接池实现要点
- 协程:使用 MySQL 协程客户端。
使用 MySQL 协程客户端,是为了能在一个 Worker 阻塞的时候,
让出 CPU 时间片去处理其他的请求,提高整个 Worker 的并发能力。
- 连接池存储介质:使用 \swoole\coroutine\channel 通道。
使用 channel 能够设置等待时间,等待其他的请求释放连接。
并且在等待期间,同样也可以让出 CPU 时间片去处理其他的请求。
假设选择 array 或 splqueue,无法等待其他的请求释放连接。
那么在高并发下的场景下,可能会出现连接池为空的现象。
如果连接池为空了,那么 pop 就直接返回 null 了,导致连接不可用。
注:因此不建议选择 array 或 splqueue。
三、连接池的具体实现
<?php
use Swoole\Coroutine\Channel;
use Swoole\Coroutine\MySQL;
class MysqlPool
{
private $min; // 最小连接数
private $max; // 最大连接数
private $count; // 当前连接数
private $connections; // 连接池
protected $freeTime; // 用于空闲连接回收判断
public static $instance;
/**
* MysqlPool constructor.
*/
public function __construct()
{
$this->min = 10;
$this->max = 100;
$this->freeTime = 10 * 3600;
$this->connections = new Channel($this->max + 1);
}
/**
* @return MysqlPool
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 创建连接
* @return MySQL
*/
protected function createConnection()
{
$conn = new MySQL();
$conn->connect([
'host' => 'mysql',
'port' => '3306',
'user' => 'root',
'password' => 'root',
'database' => 'fastadmin',
'timeout' => 5
]);
return $conn;
}
/**
* 创建连接对象
* @return array|null
*/
protected function createConnObject()
{
$conn = $this->createConnection();
return $conn ? ['last_used_time' => time(), 'conn' => $conn] : null;
}
/**
* 初始化连接
* @return $this
*/
public function init()
{
for ($i = 0; $i < $this->min; $i++) {
$obj = $this->createConnObject();
$this->count++;
$this->connections->push($obj);
}
return $this;
}
/**
* 获取连接
* @param int $timeout
* @return mixed
*/
public function getConn($timeout = 3)
{
if ($this->connections->isEmpty()) {
if ($this->count < $this->max) {
$this->count++;
$obj = $this->createConnObject();
} else {
$obj = $this->connections->pop($timeout);
}
} else {
$obj = $this->connections->pop($timeout);
}
return $obj['conn']->connected ? $obj['conn'] : $this->getConn();
}
/**
* 回收连接
* @param $conn
*/
public function recycle($conn)
{
if ($conn->connected) {
$this->connections->push(['last_used_time' => time(), 'conn' => $conn]);
}
}
/**
* 回收空闲连接
*/
public function recycleFreeConnection()
{
// 每 2 分钟检测一下空闲连接
swoole_timer_tick(2 * 60 * 1000, function () {
if ($this->connections->length() < intval($this->max * 0.5)) {
// 请求连接数还比较多,暂时不回收空闲连接
return;
}
while (true) {
if ($this->connections->isEmpty()) {
break;
}
$connObj = $this->connections->pop(0.001);
$nowTime = time();
$lastUsedTime = $connObj['last_used_time'];
// 当前连接数大于最小的连接数,并且回收掉空闲的连接
if ($this->count > $this->min && ($nowTime - $lastUsedTime > $this->freeTime)) {
$connObj['conn']->close();
$this->count--;
} else {
$this->connections->push($connObj);
}
}
});
}
}
$httpServer = new swoole_http_server('127.0.0.1',9501);
$httpServer->set(['work_num' => 1]);
$httpServer->on('WorkerStart', function ($request, $response) {
MysqlPool::getInstance()->init()->recycleFreeConnection();
});
$httpServer->on('Request', function ($request, $response){
$conn = MysqlPool::getInstance()->getConn();
$conn->query('SELECT * FROM fa_admin WHERE id=1');
MysqlPool::getInstance()->recycle($conn);
});
$httpServer->start();
四、总结
- 定时维护空闲连接到最小值。
- 使用用完数据库连接之后,需要手动回收连接到连接池。
- 使用 channel 作为连接池的存储介质。
如何在 Swoole 中优雅的实现 MySQL 连接池的更多相关文章
- 用swoole简单实现MySQL连接池
MySQL连接池 在传统的网站开发中,比如LNMP模式,由Nginx的master进程接收请求然后分给多个worker进程,每个worker进程再链接php-fpm的master进程,php-fpm再 ...
- 转 Swoole】用swoole简单实现MySQL连接池
MySQL连接池 在传统的网站开发中,比如LNMP模式,由Nginx的master进程接收请求然后分给多个worker进程,每个worker进程再链接php-fpm的master进程,php-fpm再 ...
- Django db使用MySQL连接池
Django db使用MySQL连接池 Sep 25 2016 Django db模块本身不支持MySQL连接池,只有一个配置CONN_MAX_AGE连接最大存活时间,如果WSGI服务器使用了线程池技 ...
- 如何在MyBatis中优雅的使用枚举
问题 在编码过程中,经常会遇到用某个数值来表示某种状态.类型或者阶段的情况,比如有这样一个枚举: public enum ComputerState { OPEN(10), //开启 CLOSE( ...
- Swoole MySQL 连接池的实现
目录 概述 代码 扩展 小结 概述 这是关于 Swoole 入门学习的第八篇文章:Swoole MySQL 连接池的实现. 第七篇:Swoole RPC 的实现 第六篇:Swoole 整合成一个小框架 ...
- tomcat中使用mysql连接池的配置
1.下载相应的jar包,添加到工程中 需要下载的包主要有commons-pool2-2.2 commons-dbcp2-2.0.1-src commons-dbcp2-2.0.1 commons-c ...
- python中实现mysql连接池
python中实现mysql连接池 import pymysql from DBUtils.PooledDB import PooledDB MYSQL_HOST = 'localhost' USER ...
- 实现一个协程版mysql连接池
实现一个协程版的mysql连接池,该连接池支持自动创建最小连接数,自动检测mysql健康:基于swoole的chanel. 最近事情忙,心态也有点不积极.技术倒是没有落下,只是越来越不想写博客了.想到 ...
- Swoole4-swoole创建Mysql连接池
一 .什么是mysql连接池 场景:每秒同时有1000个并发,但是这个mysql同时只能处理400个连接,mysql会宕机. 解决方案:连接池,这个连接池建立了200个和mysql的连接,这1000个 ...
随机推荐
- N皇后问题算法
N皇后问题的两种主要算法是试探回溯法和位运算法.前一种是经典算法,后一种是目前公认的最高效算法,后者比前者效率提高了至少一个数量级.很多问题可以借鉴位运算的思想. 以下是转载的我认为写的比较好的一篇N ...
- c++动态绑定的技术实现
1 什么是动态绑定 有一个基类,两个派生类,基类有一个virtual函数,两个派生类都覆盖了这个虚函数.现在有一个基类的指针或者引用,当该基类指针或者引用指向不同的派生类对象时,调用该虚函数,那么最终 ...
- 已知段地址,求CPU寻址范围
已知段地址为0001H,仅通过变化偏移地址寻址,则CPU的寻址范围是? 物理地址 = 段地址×16 + 偏移地址 所以物理地址的范围是[16×1H+0H, 16×1H+FFFFH] 也就是[10H×1 ...
- 开启unity3D的学习之路
2014年5月11号.我開始了我的Unity3D的学习之路.我将在此记录我学习过程中各个进程,这样在将来的某天,自己忘记了某部分内容时.也能够回过头来复习一下.
- Allegro PCB中添加汉字
注明出处:http://www.cnblogs.com/einstein-2014731/p/5650943.html Cadence用起来比AltiumDesigner要麻烦些,但是也更开放,更灵活 ...
- springcloud 研发规范
1) 程序结构规范 1: Facade-Stub:包含所有对外提供服务的借口定义,并对外提供 2: Façade:实现Façade-Stub里面定义的全部借口,可以调用Service模块和Commo ...
- 在ubuntu怎样修改默认的编码格式
ubuntu修改系统默认编码的方法是: 1. 参考 /usr/share/i18n/SUPPORTED 编辑/var/lib/locales/supported.d/* gedit /var/lib/ ...
- g2o的一般过程
1.自己定义顶点类.边类或者用已经有的.1.1定义顶点例子class CurveFittingVertex: public g2o::BaseVertex<3, Eigen::Vector3d& ...
- Contiki-Timer 概述
Contiki有一个clock模块和一系列timer模块:timer,stimer,ctimer,etimer,和rtimer. 一.clock模块 clock模块提供一些处理系统时间的函数,还有一些 ...
- Kbuntu16.04利用快捷键调用终端Konsole
之前用其他linux,可以按ctrl alt t三个键快速调用终端.但是我用Kbuntu16.04这个版本的时候却不行.于是跑去自定义了一下下. System Settings --> Wo ...