# MySQL的连接池、异步、断线重连
### MySQL长连接
MySQL短连接每次请求操作数据库都需要建立与MySQL服务器建立TCP连接,这是需要时间开销的。TCP连接需要3次网络通信。这样就增加了一定的延时和额外的IO消耗。请求结束后会关闭MySQL连接,还会发生3/4次网络通信。
> close操作不会增加响应延时,原因是close后是由操作系统自动进行通信的,应用程序感知不到
长连接就可以避免每次请求都创建连接的开销,节省了时间和IO消耗。提升了PHP程序的性能。
### 断线重连
在cli环境下,PHP程序需要长时间运行,客户端与MySQL服务器之间的TCP连接是不稳定的。
- MySQL-Server会在一定时间内自动切断连接
- PHP程序遇到空闲期时长时间没有MySQL查询,MySQL-Server也会切断连接回收资源
- 其他情况,在MySQL服务器中执行kill process杀掉某个连接,MySQL服务器重启
这时PHP程序中的MySQL连接就失效了。如果仍然执行mysql_query,就会报一个“MySQL server has gone away”的错误。程序处理不到就直接遇到致命错误并退出了。所以PHP程序中需要断线重连。
有很多人提出了mysql_ping的方案,每次mysql_query进行连接检测或者定时连接检测。这个方案不是最好的。原因是
- mysql_ping需要主动侦测连接,带来了额外的消耗
- 定时执行mysql_ping不能解决问题,如刚刚执行过mysql_ping检测之后,连接就关闭了
最佳的方案是,进行断线重连 。它的原理是:
1. mysql_query执行后检测返回值
1. 如果mysql_query返回失败,检测错误码发现为2006/2013(这2个错误表示连接失败),再执行一次mysql_connect
1. 执行mysql_connect后,重新执行mysql_query,这时必然会成功,因为已经重新建立了连接
1. 如果mysql_query返回成功,那么连接是有效的,这是一次正常的调用
> 可参考[swoole_framework中的代码](https://github.com/swoole/framework/blob/master/libs/Swoole/Database/MySQL.php)
### MySQL异步
MySQL异步是指将MySQL连接事件驱动化,这样就编程了非阻塞IO。数据库操作并不会阻塞进程,在MySQL-Server返回结果时再执行对应的逻辑。
有几个点需要注意一下:
- 异步MySQL并没有节省SQL执行的时间
- 一个MySQL连接同时只能执行1个SQL,如果异步MySQL存在并发那么必须创建多个MySQL连接
异步回调程序中,异步MySQL并没有提升性能。异步最大的好处是可以高并发,如果并发1万个请求,那么就需要建立1万个MySQL连接,这会给MySQL-Server带来巨大的压力。
> MySQL是根据连接数分配资源的,一个连接需要开启一个线程。1000连接那么需要维持1000线程才可以。线程数量增加后,线程间切换会占用大量CPU资源
MySQL短连接反而不会出现此问题,因为短连接在使用完后就释放了。不会占用MySQL-Server的连接资源
虽然应用层代码使用异步回调避免了自身的阻塞,实际上真正的瓶颈是数据库服务器。异步MySQL还带来了额外的编程复杂度,所以除非是特殊场景的需求,否则不建议使用异步MySQL。
如果程序中坚持要使用异步,那么必须是异步MySQL+连接池的形式。超过规定的MySQL最大连接后,应当对SQL请求进行排队,而不是创建新连接,避免大量并发请求导致MySQL服务器崩溃。
### MySQL连接池
连接池是可以有效降低MySQL-Server负载的。原理是 连接池使用一个共享资源的模式,如并发100个请求,实际上并不是每个请求的所有时间都在执行SQL查询。这样100个请求,共享20个MySQL连接就可以满足需求了。当一个请求操作完数据库后,开始进入模板渲染等流程,这时就会释放数据库连接给其他的请求使用。
连接池仅在超大型应用中才有价值。普通的应用采用MySQL长连接方案,每个php-fpm创建一个MySQL连接,每台机器开启100个php-fpm进程。如果有10台机器,每台机器并发的请求为100。实际上只需要创建1000个MySQL连接就能满足需求,数据库的压力并不大。即使有100台机器,硬件配置好的存储服务器依然可以承受。
达到数百或者数千台应用服务器时,MySQL服务器就需要维持十万级的连接。这时数据库的压力就会非常大了。连接池技术就可以派上用场了,可以大大降低数据库连接数。
> 基于swoole的AsyncTask模块实现的连接池是完美方案,编程简单,没有数据同步和锁的问题。甚至可以多个服务共享连接池。缺点是1, 灵活性不如多线程连接池,无法动态增减连接。2, 有一次进程间通信的开销。
node.js/ngx_lua等在多进程的模式下,无法开发出真正的连接池,除非也像swoole_task这样来实现
| Swoole流程 |
|-----|

- Swoole
- 入门指引
- 环境依赖
- 编译安装
- 编译参数
- 常见错误
- 版本更新记录
- 1.7.12
- 1.7.13
- 1.7.14
- 1.7.15
- 1.7.16
- 1.7.17
- 开发者列表
- 新特性使用
- 1.7.16 使用迭代器遍历Server所有连接
- 1.7.5 在Server中使用swoole_table
- 1.7.5 swoole_client支持sendfile接口
- 1.7.4 SSL隧道加密TCP-Server
- 1.7.4 task进程中使用毫秒定时器
- 1.7.3 固定包头+包体协议自动分包
- 1.7.3 onTask直接return取代finish函数
- 1.7.2 swoole_process多进程模块的使用
- 1.7.2 task进程使用消息队列
- 项目路线图
- 提交错误报告
- 内核参数调整
- 周边相关项目
- 常见问题
- 升级swoole版本的常见问题
- 生成可分发的二进制swoole版本
- Connection refused是怎么回事
- Resource temporarily unavailable [11]
- Cannot assign requested address [99]
- pcre.h: No such file or directory
- 在phpinfo中有在php-m中没有
- swoole与node.js相比有哪些优势
- swoole与golang相比有哪些优势
- my_global.h: No such file or directory
- Server
- 函数列表
- swoole_server::__construct
- swoole_server::set
- swoole_server::on
- swoole_server::addListener
- swoole_server::addProcess
- swoole_server::listen
- swoole_server::handler
- swoole_server::start
- swoole_server::reload
- swoole_server::shutdown
- swoole_server::addtimer
- swoole_server::deltimer
- swoole_server::tick
- swoole_server::after
- swoole_server::clearTimer
- swoole_server::close
- swoole_server::send
- swoole_server::sendfile
- swoole_server::sendto
- swoole_server::sendwait
- swoole_server::sendMessage
- swoole_server::connection_info
- swoole_server::connection_list
- swoole_server::bind
- swoole_server::stats
- swoole_server::task
- swoole_server::taskwait
- swoole_server::finish
- swoole_server::heartbeat
- swoole_get_mysqli_sock
- swoole_set_process_name
- swoole_version
- swoole_strerror
- swoole_errno
- swoole_get_local_ip
- 属性列表
- swoole_server::$setting
- swoole_server::$master_pid
- swoole_server::$manager_pid
- swoole_server::$worker_id
- swoole_server::$worker_pid
- swoole_server::$taskworker
- swoole_server::$connections
- 配置选项
- reactor_num
- worker_num
- max_request
- max_conn (max_connection)
- task_worker_num
- task_ipc_mode
- task_max_request
- task_tmpdir
- dispatch_mode
- message_queue_key
- daemonize
- backlog
- log_file
- heartbeat_check_interval
- heartbeat_idle_time
- open_eof_check
- open_eof_split
- package_eof
- open_length_check
- package_max_length
- open_cpu_affinity
- cpu_affinity_ignore
- open_tcp_nodelay
- tcp_defer_accept
- ssl_cert_file
- user
- group
- chroot
- 事件回调函数
- onStart
- onShutdown
- onWorkerStart
- onWorkerStop
- onTimer
- onConnect
- onReceive
- onClose
- onTask
- onFinish
- onPipeMessage
- onWorkerError
- onManagerStart
- onManagerStop
- 高级特性
- 改变Worker进程的用户/组
- 回调函数中的from_id和fd
- Buffer和EOF_Check的使用
- Worker与Reactor通信模式
- TCP-Keepalive死连接检测
- TCP服务器心跳维持方案
- 多端口监听的使用
- 捕获Server运行期致命错误
- swoole_server的3种运行模式介绍
- swoole_server中对象的4层生命周期
- 在worker进程内监听一个Server端口
- 常见问题
- 为什么不要send完后立即close
- 如何在回调函数中访问外部的变量
- swoole_server中内存管理机制
- 是否可以共用1个redis或mysql连接
- 关于onConnect/onReceive/onClose顺序
- 压力测试
- Nginx/Golang/Swoole/Node.js的性能对比
- 并发10万TCP连接的测试
- 预定义常量
- php.ini选项
- Client
- 方法列表
- swoole_client::__construct
- swoole_client::set
- swoole_client::on
- swoole_client::connect
- swoole_client::isConnected
- swoole_client::getsockname
- swoole_client::getpeername
- swoole_client::send
- swoole_client::sendto
- swoole_client::sendfile
- swoole_client::recv
- swoole_client::close
- 属性列表
- swoole_client::$errCode
- swoole_client::$sock
- 并行
- swoole_client_select
- TCP客户端异步连接
- SWOOLE_KEEP建立TCP长连接
- Process
- 方法列表
- swoole_process::__construct
- swoole_process::start
- swoole_process::name
- swoole_process::exec
- swoole_process::write
- swoole_process::read
- swoole_process::useQueue
- swoole_process::push
- swoole_process::pop
- swoole_process::close
- swoole_process::exit
- swoole_process::kill
- swoole_process::wait
- swoole_process::daemon
- swoole_process::signal
- AsyncIO
- 异步文件系统IO
- swoole_async_readfile
- swoole_async_writefile
- swoole_async_read
- swoole_async_write
- swoole_async_dns_lookup
- EventLoop
- swoole_event_add
- swoole_event_set
- swoole_event_del
- swoole_event_exit
- swoole_event_wait
- swoole_event_write
- 异步毫秒定时器
- swoole_timer_add
- swoole_timer_del
- swoole_timer_tick
- swoole_timer_after
- swoole_timer_clear
- Memory
- Lock
- swoole_lock::__construct
- swoole_lock::lock
- swoole_lock::trylock
- swoole_lock::unlock
- swoole_lock::lock_read
- swoole_lock::trylock_read
- Buffer
- swoole_buffer::__construct
- swoole_buffer::append
- swoole_buffer::substr
- swoole_buffer::clear
- swoole_buffer::expand
- swoole_buffer::write
- Table
- swoole_table::__construct
- swoole_table::column
- swoole_table::create
- swoole_table::set
- swoole_table::incr
- swoole_table::decr
- swoole_table::get
- swoole_table::del
- swoole_table::lock
- swoole_table::unlock
- 常量列表
- HttpServer
- swoole_http_server
- swoole_http_server::on
- swoole_http_server::start
- swoole_http_server::setGlobal
- swoole_http_request
- swoole_http_request::$header
- swoole_http_request::$server
- swoole_http_request::$get
- swoole_http_request::$post
- swoole_http_request::$cookie
- swoole_http_request::$files
- swoole_http_request::rawContent
- swoole_http_response
- swoole_http_response::header
- swoole_http_response::cookie
- swoole_http_response::status
- swoole_http_response::gzip
- swoole_http_response::write
- swoole_http_response::end
- 常见问题
- CURL发送POST请求服务器端超时
- WebSocket
- 回调函数
- onHandShake
- onOpen
- onMessage
- 函数列表
- swoole_websocket_server::push
- 预定义常量
- 高级
- Swoole的实现
- Reactor线程
- Manager进程
- Worker进程
- Reactor、Worker、Task的关系
- Task/Finish特性的用途
- C/C++开发者如何使用Swoole
- 在php-fpm或apache中使用swoole在php-fpm或apache中使用swoole
- Swoole异步与同步的选择
- TCP/UDP压测工具
- swoole服务器如何做到无人值守100
- MySQL的连接池、异步、断线重连
- 其他
- Swoole社区
- 加入Swoole开发组
- 附录:Linux信号列表
- 附录:Linux错误信息(errno)列表
- 附录:TCP连接的状态
- 附录:tcpdump抓包工具的使用
- 附录:strace工具的使用
- 附录:编译PHP扩展的相关工具
- 备用:已移除的历史特性
- onMasterConnect
- onMasterClose
- 历史:版本更新记录
- v1.5
- v1.6
- v1.7
- v1.7.5
- v1.7.6
- v1.7.7
- v1.7.8
- v1.7.9
- v1.7.10
- v1.7.11
- Swoole-framework
- 开发指南
- 安装Swoole框架和扩展
- 数据库Model类
- model::get
- model::set
- model::del
- model::put
- model::gets
- model::sets
- model::dels
- model::all
- model::count
- model::exists
- model($model_name)
- table($table_name)
- 数据库ORM接口
- Socket网络开发
- TCP服务器
- Web服务器
- WebSocket
- Nginx+Swoole服务器配置
- Apache+Swoole服务器配置
- 控制器Controller
- 命名空间
- 文件上传组件
- Redis
- Database
- Swoole\Database::insert
- 框架规范
- 目录规范
- 自定义路由
- URL映射规则
- 示例程序
- 服务器端程序(Server)
- http_server
- app_server
- soa_server
- websocket_server
- comet_server
- 配置文件
