DbPool.php 1.9 KB
<?php

namespace Lib;

use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;

/**
 * db 池 不主动释放连接
 * @author:dc
 * @time 2023/2/13 15:03
 * Class DbPool
 * @package Lib
 */
class DbPool {

    use DbQuery;

    /**
     * @var \Swoole\Database\PDOPool
     */
    static $pool = null;

    /**
     * 获取到的连接
     * @var array
     */
    public static $clientAll = [];

    /**
     * 连接的数量
     * @var int
     */
    public static $clientNumber = 1024;

    /**
     * 实例
     * DbPool constructor.
     */
    public function __construct()
    {

        if(!static::$pool){
            $pdoconfig = (new PDOConfig)
                ->withHost(DB_HOST)
                ->withPort(DB_PORT)
                ->withDbName(DB_DATABASE)
                ->withCharset('utf8mb4')
                ->withUsername(DB_USER)
                ->withPassword(DB_PASSWORD)
                ->withOptions([
                    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
                    \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8mb4'",
                    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
                    \PDO::ATTR_TIMEOUT => 30,
                ]);

            static::$pool = new PDOPool($pdoconfig,self::$clientNumber);
        }


    }

    public function getClient()
    {
        $id = \co::getCid();
        if(empty(static::$clientAll[$id])){
            static::$clientAll[$id] = self::$pool->get();
        }
        return static::$clientAll[$id];
    }


    /**
     * 结束
     */
    public function __destruct(){
//        $this->close();
    }

    /**
     * 关闭链接
     * @author:dc
     * @time 2024/5/30 10:30
     */
    public function close(){
        $id = \co::getCid();
        if (isset(static::$clientAll[$id])){
            self::$pool->put(static::$clientAll[$id]);
        }
        unset(static::$clientAll[$id]);
    }



}