当前位置: 首页 > 后端技术 > PHP

基于swoole的通用连接池-数据库连接池

时间:2023-03-30 05:44:09 PHP

连接池open-smf/connection-pool是基于swoole的通用连接池,常用作数据库连接池。Dependency依赖版本PHP>=7.0.0Swoole>=4.2.9Recommended4.2.13+安装通过Composer安装。composerrequire"open-smf/connection-pool:~1.0"使用更多示例。AvailableConnector连接器说明CoroutineMySQLConnectorSwoole\Coroutine\MySQL实例CoroutinePostgreSQLConnectorSwoole\Coroutine\PostgreSQL实例,编译Swoole时需要添加参数--enable-coroutine-postgresqlCoroutineRedisConnectorSwoole\Coroutine\Redis实例PhpRedisConnectorRedis实例,需要安装redisPDOConnectorPDO实例,需要安装PDOYourConnectorYourConnector必须实现接口ConnectorInterface,任何对象都可以作为连接实例基本用法useSmf\ConnectionPool\ConnectionPool;useSmf\ConnectionPool\Connectors\CoroutineMySQLConnector;useSwoole\Coroutine\MySQL;go(function(){//MySQL连接数区间:[10,30]$pool=newConnectionPool(['minActive'=>10,'maxActive'=>30,'maxWaitTime'=>5,'maxIdleTime'=>20,'idleCheckInterval'=>10,],newCoroutineMySQLConnector,//指定连接器实例,这里使用协程MySQL连接器,这样就可以创建一个协程MySQL数据库连接池['host'=>'127.0.0.1','port'=>'3306','user'=>'root','password'=>'xy123456','database'=>'mysql','timeout'=>10,'charset'=>'utf8mb4','strict_type'=>true,'fetch_mode'=>是的,]);echo"初始化连接池...\n";$池->初始化();defer(function()use($pool){echo"关闭连接池...\n";$pool->close();});echo"从连接池中借用连接...\n";/**@varMySQL$connection*/$connection=$pool->borrow();//执行查询语句$status=$connection->query('SHOWSTATUSLIKE"Threads_connected"');echo"连接用完后,尽快归还...\n";$池->返回($连接);var_dump($status);});SwooleServer中的使用useSmf\ConnectionPool\ConnectionPool;useSmf\ConnectionPool\ConnectionPoolTrait;useSmf\ConnectionPool\Connectors\CoroutineMySQLConnector;useSmf\ConnectionPool\Connectors\PhpRedisConnector;useSwoole\Coroutine\MySQL;useSwoole\Http\Request;使用Swoole\Http\R响应;使用Swoole\Http\Server;类HttpServer{使用ConnectionPoolTrait;受保护的$swoole;公共函数__construct(string$host,int$port){$this->swoole=newServer($host,$port);$this->setDefault();$this->bindWorkerEvents();$this->bindHttpEvent();}protectedfunctionsetDefault(){$this->swoole->set(['daemonize'=>false,'dispatch_mode'=>1,'max_request'=>8000,'open_tcp_nodelay'=>true,'reload_async'=>是的,'max_wait_time'=>60,'enable_reuse_port'=>true,'enable_coroutine'=>true,'http_compression'=>false,'enable_static_handler'=>false,'buffer_output_size'=>4*1024*1024,'worker_num'=>4,//每个Worker持有一个独立的连接池]);}protectedfunctionbindHttpEvent(){$this->swoole->on('Request',function(Request$request,Response$response){$pool1=$this->getConnectionPool('mysql');/**@varMySQL$mysql*/$mysql=$pool1->borrow();$status=$mysql->query('SHOWSTATUSLIKE"Threads_connected"');//返回$pool1->return($mysql);$pool2=$this->getConnectionPool('redis');/**@varRedis$redis*/$redis=$pool2->borrow();$clients=$redis->info('Clients');//返回$pool2->return($redis)在连接用完后尽快返回;$json=['status'=>$status,'clients'=>$clients,];//其他逻辑//...$response->header('Content-Type','application/json');$response->end(json_encode($json));});}protectedfunctionbindWorkerEvents(){$createPools=function(){//拥有的MySQL连接数区间:[4workers*2=8,4workers*10=40]$pool1=newConnectionPool(['minActive'=>2,'maxActive'=>10,],newCoroutineMySQLConnector,['host'=>'127.0.0.1','port'=>'3306','user'=>'root','password'=>'xy123456','database'=>'mysql','timeout'=>10,'charset'=>'utf8mb4','strict_type'=>true,'fetch_mode'=>true,]);$pool1->init();$this->addConnectionPool('mysql',$pool1);之间:[4名工人*5=20,4名工人*20=80]$pool2=newConnectionPool(['minActive'=>5,'maxActive'=>20,],newPhpRedisConnector,['host'=>'127.0.0.1','端口'=>'6379','数据库'=>0,'密码'=>null,]);$pool2->init();$this->addConnectionPool('redis',$pool2);};$closePools=function(){$this->closeConnectionPools();};//Worker启动时创建MySQL和Redis连接池$this->swoole->on('WorkerStart',$createPools);//当Worker正常退出或出错时,关闭连接池并释放连接$this->swoole->on('WorkerStop',$closePools);$this->swoole->on('WorkerError',$closePools);}publicfunctionstart(){$this->swoole->;开始();}}//启用CoroutineRuntime允许PhpRedis展开一键协程Swoole\Runtime::enableCoroutine(true);$server=newHttpServer('0.0.0.0',5200);$server->start();我已经在生产环境中使用过,并且已经贡献到Github,性能稳定。欢迎Star&PR