Swoole MySQL 連線池的實現

新亮筆記發表於2019-05-27

概述

這是關於 Swoole 入門學習的第八篇文章:Swoole MySQL 連線池的實現。

收到讀者的諮詢,這情況大家可能也會有,所以就在這說說:

“亮哥,我今年30歲了,有點中年危機,最近有點焦慮,發現工作雖然很忙,但是沒感覺能力有所提升,整天都有寫不完的業務程式碼,時間緊有時程式碼質量也不怎麼樣,知道還有很多改進空間,但一直沒時間改,主要是後面專案壓著,馬上又要進入開發了,這種情況怎麼辦?”

首先,我是菜雞,觀點不喜勿噴,那我就說下自己的看法:

上面的描述比較主觀,人呀有時候發現不了自己的能力很正常,有時候有能力了並不是馬上就能顯現的,而是到了某個階段後突然發現,哇塞,原來自己這麼厲害。

當然能力也分很多種,比如專業能力,快速學習能力,進度把控能力,還有自信也是一種能力,不要臉是一種能力,堅持不要臉更是一種能力。

其實能力提升最快的還是靠工作實踐,悄悄問問自己加入了很多大牛的微信群,能力提升了嗎?看書自學不實踐是不是吸收的也不多。

如果非要給一個具體的方案,那就是在團隊內多分享吧,因為在分享前你會做充分的準備來避免分享時出醜,即使有時候自己知道,當講出來的時候就不是那麼回事了。

前期分享可以是看稿,後期練習無稿分享。

然後,再多說一點,30了給自己一個目標,不要盲目每天就是學學學,比如目標是技術專家,目標是業務專家,都很好呀,當然目標與自己性格有關也不是一成不變的。

圍繞著目標設定一些計劃,不要以為每天的學學學,就覺得其他的一切就自然而來,其中還有很多機遇和人脈的因素。

最後,如果實在感覺壓得喘不過氣,就換個環境吧,別和自己過不去。

開始今天的文章,這篇文章實現了 Swoole MySQL 連線池,程式碼是在《Swoole RPC 的實現》文章的基礎上進行開發的。

先回顧上篇文章的內容:

  • 實現了 HTTP / TCP 請求
  • 實現了 同步 / 非同步 請求
  • 分享了 OnRequest.php、OnReceive.php 原始碼
  • 業務邏輯 Order.php 中返回的是假資料

本篇文章主要的功能點:

  • 業務邏輯 Order.php 中返回 MySQL 資料庫中的資料。
  • Task 啟用了協程
  • 支援 主/從 資料庫配置
  • 實現資料庫連線池
  • 實現資料庫 CURD

程式碼

Order.php

<?php

if (!defined('SERVER_PATH')) exit("No Access");

class Order
{
    public function get_list($uid = 0, $type = 0)
    {
        //TODO 業務程式碼

        $rs[0]['order_code'] = '1';
        $rs[0]['order_name'] = '訂單1';

        $rs[1]['order_code'] = '2';
        $rs[1]['order_name'] = '訂單2';

        $rs[2]['order_code'] = '3';
        $rs[2]['order_name'] = '訂單3';

        return $rs;
    }
}

修改成:

class Order
{
    private $mysql;
    private $table;

    public function __construct()
    {
        $pool = MysqlPool::getInstance();
        $this->mysql = $pool->get();
        $this->table = 'order';
    }

    public function add($code = '', $name = '')
    {
        //TODO 驗證
        return $this->mysql->insert($this->table, ['code' => $code, 'name' => $name]);
    }

    public function edit($id = 0,  $name='')
    {
        //TODO 驗證
        return $this->mysql->update($this->table, ['name' => $name], ['id' => $id]);
    }

    public function del($id = 0)
    {
        //TODO 驗證
        return $this->mysql->delete($this->table, ['id' => $id]);
    }

    public function info($code = '')
    {
        //TODO 驗證
        return $this->mysql->select($this->table, ['code' => $code]);
    }
}

Task 啟用協程

一、需要新增兩項配置:

enable_coroutine      = true
task_enable_coroutine = true

二、回撥引數發生改變

$serv->on('Task', function ($serv, $task_id, $src_worker_id, $data) {
   ...
});

修改成:

$serv->on('Task', function ($serv, $task) {
    $task->worker_id; //來自哪個`Worker`程式
    $task->id; //任務的編號
    $task->data; //任務的資料
});

資料庫 主/從 配置

Mysql.php

<?php

if (!defined('SERVER_PATH')) exit("No Access");

$db['default']['pool_size']        = 3; //連線池個數
$db['default']['pool_get_timeout'] = 0.5; //獲取連線池超時時間
$db['default']['timeout']          = 0.5; //資料庫建立連線超時時間
$db['default']['charset']          = 'utf8'; //字符集
$db['default']['strict_type']      = false; //開啟嚴格模式
$db['default']['fetch_mode']       = true; //開啟fetch模式

$config['master']             = $db['default'];
$config['master']['host']     = '127.0.0.1';
$config['master']['port']     = 3306;
$config['master']['user']     = 'root';
$config['master']['password'] = '123456';
$config['master']['database'] = 'demo';

$config['slave']             = $db['default'];
$config['slave']['host']     = '127.0.0.1';
$config['slave']['port']     = 3306;
$config['slave']['user']     = 'root';
$config['slave']['password'] = '123456';
$config['slave']['database'] = 'demo';

資料庫連線池

MysqlPool.php

<?php

if (!defined('SERVER_PATH')) exit("No Access");

class MysqlPool
{
    private static $instance;
    private $pool;
    private $config;

    public static function getInstance($config = null)
    {
        if (empty(self::$instance)) {
            if (empty($config)) {
                throw new RuntimeException("MySQL config empty");
            }
            self::$instance = new static($config);
        }
        return self::$instance;
    }

    public function __construct($config)
    {
        if (empty($this->pool)) {
            $this->config = $config;
            $this->pool = new chan($config['master']['pool_size']);
            for ($i = 0; $i < $config['master']['pool_size']; $i++) {
                go(function() use ($config) {
                    $mysql = new MysqlDB();
                    $res = $mysql->connect($config);
                    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['master']['pool_get_timeout']);
            if (false === $mysql) {
                throw new RuntimeException("Pop mysql timeout");
            }
            defer(function () use ($mysql) { //釋放
                $this->pool->push($mysql);
            });
            return $mysql;
        } else {
            throw new RuntimeException("Pool length <= 0");
        }
    }
}

資料庫 CURD

MysqlDB.php

<?php

if (!defined('SERVER_PATH')) exit("No Access");

class MysqlDB
{
    private $master;
    private $slave;
    private $config;

    public function __call($name, $arguments)
    {
        if ($name != 'query') {
            throw new RuntimeException($name.":This command is not supported");
        } else {
            return $this->_execute($arguments[0]);
        }
    }

    public function connect($config)
    {
        //主庫
        $master = new Swoole\Coroutine\MySQL();
        $res = $master->connect($config['master']);
        if ($res === false) {
            throw new RuntimeException($master->connect_error, $master->errno);
        } else {
            $this->master = $master;
        }

        //從庫
        $slave = new Swoole\Coroutine\MySQL();
        $res = $slave->connect($config['slave']);
        if ($res === false) {
            throw new RuntimeException($slave->connect_error, $slave->errno);
        } else {
            $this->slave = $slave;
        }

        $this->config = $config;
        return $res;
    }

    public function insert($table = '', $data = [])
    {
        $fields = '';
        $values = '';
        $keys = array_keys($data);
        foreach ($keys as $k) {
            $fields .= "`".addslashes($k)."`, ";
            $values .= "'".addslashes($data[$k])."', ";
        }
        $fields = substr($fields, 0, -2);
        $values = substr($values, 0, -2);
        $sql = "INSERT INTO `{$table}` ({$fields}) VALUES ({$values})";
        return $this->_execute($sql);
    }

    public function update($table = '', $set = [], $where = [])
    {
        $arr_set = [];
        foreach ($set as $k => $v) {
            $arr_set[] = '`'.$k . '` = ' . $this->_escape($v);
        }
        $set = implode(', ', $arr_set);
        $where = $this->_where($where);
        $sql = "UPDATE `{$table}` SET {$set} {$where}";
        return $this->_execute($sql);
    }

    public function delete($table = '', $where = [])
    {
        $where = $this->_where($where);
        $sql = "DELETE FROM `{$table}` {$where}";
        return $this->_execute($sql);
    }

    public function select($table = '',$where = [])
    {
        $where = $this->_where($where);
        $sql = "SELECT * FROM `{$table}` {$where}";
        return $this->_execute($sql);
    }

    private function _where($where = [])
    {
        $str_where = '';
        foreach ($where as $k => $v) {
            $str_where .= " AND `{$k}` = ".$this->_escape($v);
        }
        return "WHERE 1 ".$str_where;
    }

    private function _escape($str)
    {
        if (is_string($str)) {
            $str = "'".$str."'";
        } elseif (is_bool($str)) {
            $str = ($str === FALSE) ? 0 : 1;
        } elseif (is_null($str)) {
            $str = 'NULL';
        }
        return $str;
    }

    private function _execute($sql)
    {
        if (strtolower(substr($sql, 0, 6)) == 'select') {
            $db = $this->_get_usable_db('slave');
        } else {
            $db = $this->_get_usable_db('master');
        }
        $result = $db->query($sql);
        if ($result === true) {
            return [
                'affected_rows' => $db->affected_rows,
                'insert_id'     => $db->insert_id,
            ];
        }
        return $result;
    }

    private function _get_usable_db($type)
    {
        if ($type == 'master') {
            if (!$this->master->connected) {
                $master = new Swoole\Coroutine\MySQL();
                $res = $master->connect($this->config['master']);
                if ($res === false) {
                    throw new RuntimeException($master->connect_error, $master->errno);
                } else {
                    $this->master = $master;
                }
            }
            return $this->master;
        } elseif ($type == 'slave') {
            if (!$this->slave->connected) {
                $slave = new Swoole\Coroutine\MySQL();
                $res = $slave->connect($this->config['slave']);
                if ($res === false) {
                    throw new RuntimeException($slave->connect_error, $slave->errno);
                } else {
                    $this->slave = $slave;
                }
            }
            return $this->slave;
        }
    }
}

OnWorkerStart 中呼叫

try {
    MysqlPool::getInstance(get_config('mysql'));
} catch (\Exception $e) {
    $serv->shutdown();
} catch (\Throwable $throwable) {
    $serv->shutdown();
}

客戶端傳送請求

<?php

//新增
$demo = [
    'type'  => 'SW',
    'token' => 'Bb1R3YLipbkTp5p0',
    'param' => [
        'class'  => 'Order',
        'method' => 'add',
        'param' => [
            'code' => 'C'.mt_rand(1000,9999),
            'name' => '訂單-'.mt_rand(1000,9999),
        ],
    ],
];

//編輯
$demo = [
    'type'  => 'SW',
    'token' => 'Bb1R3YLipbkTp5p0',
    'param' => [
        'class'  => 'Order',
        'method' => 'edit',
        'param' => [
            'id' => '4',
            'name' => '訂單-'.mt_rand(1000,9999),
        ],
    ],
];

//刪除
$demo = [
    'type'  => 'SW',
    'token' => 'Bb1R3YLipbkTp5p0',
    'param' => [
        'class'  => 'Order',
        'method' => 'del',
        'param' => [
            'id' => '1',
        ],
    ],
];


//查詢
$demo = [
    'type'  => 'SW',
    'token' => 'Bb1R3YLipbkTp5p0',
    'param' => [
        'class'  => 'Order',
        'method' => 'info',
        'param' => [
            'code' => 'C4649'
        ],
    ],
];

$ch = curl_init();
$options = [
    CURLOPT_URL  => 'http://10.211.55.4:9509/',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => json_encode($demo),
];
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);

擴充套件

官方協程 MySQL 客戶端手冊:

https://wiki.swoole.com/wiki/page/p-coroutine_mysql.html

大家可以嘗試使用官方提供的其他方法。

小結

Demo 程式碼僅供參考,裡面有很多不嚴謹的地方。

根據自己的需要進行修改,比如業務程式碼相關驗證,CURD 方法封裝 ...

推薦一個完善的產品,Swoole 開發的 MySQL 資料庫連線池(SMProxy):

https://github.com/louislivi/smproxy

上面的 Demo 需要原始碼的,加我微信。(選單-> 加我微信-> 掃我)

本文歡迎轉發,轉發請註明作者和出處,謝謝!

相關文章