ホームページ  >  記事  >  PHPフレームワーク  >  swooleをベースにしたmysql接続プール実装の詳細説明

swooleをベースにしたmysql接続プール実装の詳細説明

coldplay.xixi
coldplay.xixi転載
2020-12-25 17:18:167019ブラウズ

swoole フレームワークswoole で mysql 接続プールを実装する方法を紹介するコラムです

swooleをベースにしたmysql接続プール実装の詳細説明

推奨事項 (無料): swooleフレームワーク

序文

従来の nginx FPM モード PHP プログラムの場合、ワーカーが FPM をリクエストするたびに、mysql に 1 回接続します。その後、リクエストは終了します。切断します。同時実行数が少ないアプリケーションの場合は問題ありませんが、同時実行数が高いアプリケーションの場合、頻繁に接続が確立され接続が切断されるとデータベースがボトルネックとなり、多数の接続に遭遇したことがある人も多いと思います。エラーを報告します。

接続プールの利点

接続プールはロング接続モードを採用しており、常に 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[&#39;pool_size&#39;]; $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();
    }}
Database 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([
        &#39;pool_size&#39;=>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("<h1>Test</h1>");
    });
    $server->handle('/test', function ($request, $response) {
        $response->end("<h1>Test</h1>");
    });
    $server->handle('/stop', function ($request, $response) use ($server) {
        $response->end("<h1>Stop</h1>");
        $server->shutdown();
    });
    $server->start();});
ソース コード アドレス swoole-mysql-プール

#関連する無料学習の推奨事項: mysql ビデオ チュートリアル

以上がswooleをベースにしたmysql接続プール実装の詳細説明の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はlearnku.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。