国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

基于Swoole的通用連接池 - 數據庫連接池

superPershing / 1765人閱讀

摘要:連接池是一個基于的通用連接池,常被用作數據庫連接池。依賴依賴版本安裝通過安裝。使用更多示例。

連接池
open-smf/connection-pool 是一個基于Swoole的通用連接池,常被用作數據庫連接池。
依賴
依賴 版本
PHP >=7.0.0
Swoole >=4.2.9 Recommend 4.2.13+
安裝
通過Composer安裝。
composer require "open-smf/connection-pool:~1.0"
使用
更多示例。

可用的連接器

連接器 說明
CoroutineMySQLConnector SwooleCoroutineMySQL的實例
CoroutinePostgreSQLConnector SwooleCoroutinePostgreSQL的實例,編譯Swoole時需要添加參數--enable-coroutine-postgresql
CoroutineRedisConnector SwooleCoroutineRedis的實例
PhpRedisConnector Redis的實例,需要安裝redis
YourConnector YourConnector必須實現接口ConnectorInterface,任何對象均可作為連接實例

基本用法

use SmfConnectionPoolConnectionPool;
use SmfConnectionPoolConnectorsCoroutineMySQLConnector;
use SwooleCoroutineMySQL;

go(function () {
    // MySQL連接數區間:[10, 30]
    $pool = new ConnectionPool(
        [
            "minActive"         => 10,
            "maxActive"         => 30,
            "maxWaitTime"       => 5,
            "maxIdleTime"       => 20,
            "idleCheckInterval" => 10,
        ],
        new CoroutineMySQLConnector, // 指明連接器實例,這里使用協程MySQL連接器,這樣就可以創建一個協程MySQL的數據庫連接池
        [
            "host"        => "127.0.0.1",
            "port"        => "3306",
            "user"        => "root",
            "password"    => "xy123456",
            "database"    => "mysql",
            "timeout"     => 10,
            "charset"     => "utf8mb4",
            "strict_type" => true,
            "fetch_mode"  => true,
        ]
    );
    echo "初始化連接池...
";
    $pool->init();
    defer(function () use ($pool) {
        echo "關閉連接池...
";
        $pool->close();
    });

    echo "從連接池中借出連接...
";
    /**@var MySQL $connection */
    $connection = $pool->borrow();
    
    // 執行查詢語句
    $status = $connection->query("SHOW STATUS LIKE "Threads_connected"");
    
    echo "用完連接后,盡快歸還...
";
    $pool->return($connection);
    
    var_dump($status);
});

在Swoole Server中的用法

use SmfConnectionPoolConnectionPool;
use SmfConnectionPoolConnectionPoolTrait;
use SmfConnectionPoolConnectorsCoroutineMySQLConnector;
use SmfConnectionPoolConnectorsPhpRedisConnector;
use SwooleCoroutineMySQL;
use SwooleHttpRequest;
use SwooleHttpResponse;
use SwooleHttpServer;

class HttpServer
{
    use ConnectionPoolTrait;

    protected $swoole;

    public function __construct(string $host, int $port)
    {
        $this->swoole = new Server($host, $port);

        $this->setDefault();
        $this->bindWorkerEvents();
        $this->bindHttpEvent();
    }

    protected function setDefault()
    {
        $this->swoole->set([
            "daemonize"             => false,
            "dispatch_mode"         => 1,
            "max_request"           => 8000,
            "open_tcp_nodelay"      => true,
            "reload_async"          => true,
            "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持有一個獨立的連接池
        ]);
    }

    protected function bindHttpEvent()
    {
        $this->swoole->on("Request", function (Request $request, Response $response) {
            $pool1 = $this->getConnectionPool("mysql");
            /**@var MySQL $mysql */
            $mysql = $pool1->borrow();
            $status = $mysql->query("SHOW STATUS LIKE "Threads_connected"");
            // 用完連接后,盡快歸還
            $pool1->return($mysql);


            $pool2 = $this->getConnectionPool("redis");
            /**@var Redis $redis */
            $redis = $pool2->borrow();
            $clients = $redis->info("Clients");
            // 用完連接后,盡快歸還
           $pool2->return($redis);

            $json = [
                "status"  => $status,
                "clients" => $clients,
            ];
            // Other logic
            // ...
            $response->header("Content-Type", "application/json");
            $response->end(json_encode($json));
        });
    }

    protected function bindWorkerEvents()
    {
        $createPools = function () {
            // 所有的MySQL連接數區間:[4 workers * 2 = 8, 4 workers * 10 = 40]
            $pool1 = new ConnectionPool(
                [
                    "minActive" => 2,
                    "maxActive" => 10,
                ],
                new CoroutineMySQLConnector,
                [
                    "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);

            // 所有Redis連接數區間:[4 workers * 5 = 20, 4 workers * 20 = 80]
            $pool2 = new ConnectionPool(
                [
                    "minActive" => 5,
                    "maxActive" => 20,
                ],
                new PhpRedisConnector,
                [
                    "host"     => "127.0.0.1",
                    "port"     => "6379",
                    "database" => 0,
                    "password" => 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);
    }

    public function start()
    {
        $this->swoole->start();
    }
}

// 啟用協程Runtime來讓PhpRedis擴展一鍵協程化
SwooleRuntime::enableCoroutine(true);
$server = new HttpServer("0.0.0.0", 5200);
$server->start();

本人已用于生產環境,表現穩定

貢獻
Github,歡迎 Star & PR。

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://m.specialneedsforspecialkids.com/yun/31014.html

相關文章

  • SMProxy,讓你項目據庫操作快三倍!

    摘要:一個基于協議,開發的數據庫連接池。也可以通過其自身的管理機制來監視數據庫連接的數量使用情況等。超出最大連接數會采用協程掛起,等到有連接關閉再恢復協程繼續操作。 SMProxy GITHUB:https://github.com/louislivi/... Swoole MySQL Proxy 一個基于 MySQL 協議,Swoole 開發的MySQL數據庫連接池。 原理 將數據庫連接作...

    MartinHan 評論0 收藏0
  • Swoole4.x之協程變量訪問安全與協程連接實現

    摘要:訪問安全問題為什么說有訪問安全問題呢傳統地,在的的環境中,很少有遇到所謂變量安全訪問問題。上下文管理器為了解決這個問題,我們引入協程上下文管理這樣的概念,由此來實現每個協程環境內的數據隔離。 訪問安全問題 為什么說有訪問安全問題呢?傳統地,在php的的環境中,很少有Phper遇到所謂變量安全訪問問題。舉個例子,代碼大約如下: class db { protected stati...

    aisuhua 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<