您好,欢迎访问一九零五行业门户网

swoole怎么做mysql连接池

连接池定义:永不断开,要求我们的这个程序是一个常驻内存的程序。数据库连接池(connection pooling)是程序启动时建立足够的数据库连接,并将这些连接组成一个连接池,由程序动态地对池中的连接进行申请,使用,释放。
实现连接池的方法:
同步阻塞模式:
可基于swoole的asynctask模块实现的连接池,编程简单,没有数据同步和锁的问题。甚至可以多个服务共享连接池。缺点是: 1. 灵活性不如多线程连接池,无法动态增减连接 2. 有一次进程间通信的开销
协程模式:
可使用channel实现连接池。
创建10个mysql连接示例代码:
<?php/** * created by phpstorm. * user: administrator * date: 2018/11/20 * 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();
效果
推荐学习: swoole教程
以上就是swoole怎么做mysql连接池的详细内容。
其它类似信息

推荐信息