温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

swoole的mysql连接池怎么弄

发布时间:2020-12-28 09:54:07 来源:亿速云 阅读:141 作者:小新 栏目:编程语言

这篇文章给大家分享的是有关swoole的mysql连接池怎么弄的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

传统的nginx+FPM模式的PHP程序而言,每次请求FPM的worker都会连接一次mysql,然后请求结束便会断开连接。对于并发小的应用来说这不会有什么问题,但是对于高并发的应用来说,频繁建立连接Connect和销毁连接Close,数据库便会成为瓶颈,相信不少人也遇到过to many connection的mysql报错吧。

连接池的优势

连接池采用的是长连接模式,会一直保持与MySQL的连接,用完后会重新放回连接池,从而节省了建立连接和断开连接的消耗,大大降低了系统IO的消耗,一定程度上提高了程序的并发性能。如果连接池空闲,就从连接池分配一个连接,否则,请求将被加入到等待队列中。

实现

我们采用swoole实现mysql连接池

连接池类
<?php

require_once "MysqlDB.php";class MysqlPool{
    private static $instance;
    private $pool;
    private $config;
    private $pool_get_timeout;

    /**
     * 获取mysql进程池单例
     * @param null $config
     * @return MysqlPool
     */
    public static function getInstance($config = null)
    {
        if (empty(self::$instance)) {
            if (empty($config)) {
                throw new RuntimeException("mysql config is empty");
            }
            self::$instance = new static($config);
        }
        return self::$instance;
    }

    public function __construct($config)
    {
        if (empty($this->pool)) {
            $this->config = $config;
            $this->pool = new \Swoole\Coroutine\Channel($config['pool_size']);
            for ($i = 0; $i < $config['pool_size']; $i++) {
                \go(function() use ($config) {
                    $mysql = new MysqlDB();
                    $res = $mysql->connect($config['mysql']);
                    if ($res === false) {
                        throw new RuntimeException("Failed to connect mysql server");
                    } else {
                        $this->pool->push($mysql);
                    }
                });
            }
        }
    }

    public function get()
    {
        if ($this->pool->length() > 0) {
            $mysql = $this->pool->pop($this->config['pool_get_timeout']);
            if (false === $mysql) {
                throw new RuntimeException("Pop mysql timeout");
            }
            return $mysql;
        } else {
            throw new RuntimeException("Pool length <= 0");
        }
    }

    public function recycle(MysqlDB $mysql){
        $this->pool->push($mysql);
    }

    /**
     * 获取连接池长度
     * @return mixed
     */
    public function getPoolSize(){
        return $this->pool->length();
    }}
数据库DB类
<?phpclass MysqlDB{
    private $connection;

    public function connect($config)
    {
        $connection = new \Swoole\Coroutine\MySQL();
        $res = $connection->connect($config);
        if ($res === false) {
            throw new RuntimeException($connection->connect_error, $connection->errno);
        } else {
            $this->connection = $connection;
        }
        return $res;
    }


    public function query($sql){
        $result = $this->connection->query($sql);
        return $result;
    }}
在HTTP协程服务器中创建连接池
<?php
require_once "MysqlPool.php";\Co\run(function () {
    $server = new \Co\Http\Server("0.0.0.0", 9501, false);
    $pool = MysqlPool::getInstance([
        'pool_size'=>5,
        'pool_get_timeout'=>1,
        'timeout'=>1,
        'charset'=>'utf8',
        'strict_type'=>false,
        'fetch_mode'=>true,
        'mysql'=>[
            'host'=>'127.0.0.1',
            'port'=>'3306',
            'user'=>'homestead',
            'password'=>'secret',
            'database'=>'blog',
        ]
    ]);
    $server->handle('/', function ($request, $response) use ($pool){
        $mysql = $pool->get();
        $res = $mysql->query("select id,phone,username from user limit 1");
        var_dump($res);
        $pool->recycle($mysql);
        $response->end("<h2>Test</h2>");
    });
    $server->handle('/test', function ($request, $response) {
        $response->end("<h2>Test</h2>");
    });
    $server->handle('/stop', function ($request, $response) use ($server) {
        $response->end("<h2>Stop</h2>");
        $server->shutdown();
    });
    $server->start();});
源码地址 swoole-mysql-pool

感谢各位的阅读!关于“swoole的mysql连接池怎么弄”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI