zoukankan      html  css  js  c++  java
  • Mysql连接池

    摘自百度百科:
    数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新
    建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗
    漏。这项技术能明显提高对数据库操作的性能。
    在以前的apache或php-fpm中,数据库是没有连接池的,请求开始,在需要查询数据的地方开始建立数据库连
    接,之后查询数据,请求完成连接关闭。下一次请求继续重复这样的操作,弊端在于需要在每次请求中初始化数据
    库连接操作。
    在Swoole中,由于对象式持久化的,那么就可以在服务器启动初期事先建立好一定数量的数据库连接放在那,应
    用程序需要连接的时候在去获取,这样就省去了建立连接的过程。

    查看连接数量

    show processlist;

    PHP代码的编写

    <?php
    /**
    * 数据库连接池
    */
    class Pool {
    // 可用的db对象数量
    private $_avaNum = 2;
    // db对象的总数
    private $_total = 2;
    // db对象的列表
    private $_dbs = [];
    // 连接数据信息
    private $_dsn = 'mysql:host=localhost;dbname=test;charset=utf8';
    // 用户名
    private $_user = 'root';
    // 密码
    private $_pass = 'admin888';
    // 类对象
    private static $_ins = null;
    private function __construct() {
    $this->_connection();
    }
    // 连接数据库
    private function _connection() {
    for ($i = 0; $i < $this->_total; $i++) {
    $this->_dbs[] = new PDO($this->_dsn, $this->_user, $this->_pass);
    }
    }
    // 初始化
    public static function getIns() {
    if (is_null(self::$_ins)) {
    self::$_ins = new self();
    }
    return self::$_ins;
    }
    /**
    * 查询
    * @param string $sql
    */
    public function findAll(string $sql) {
    if ($this->_avaNum <= 0)
    throw new Exception('没有可用的连接数');
    // 池中取db对象
    $this->_avaNum--;
    $pdo = array_pop($this->_dbs);
    $row = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    // db放入池中
    $this->_avaNum++;
    array_unshift($this->_dbs, $pdo);
    return $row;
    }
    }
    // 创建一个httpserver对象
    $http = new swoole_http_server('0.0.0.0', 6060);
    // 设置worker进程数量
    $http->set(
    [
    # 进程数量
    'worker_num' => 1,
    # worker进程最大的处理数量,达到将会销毁
    'max_request' => 1000,
    # task数量
    #'task_worker_num' => 10
    ]
    );
    // worker进程启动的时候启动
    3、效果
    命令行执行脚本
    浏览器中查看
    $http->on(
    'WorkerStart', function (swoole_server $server, int $worker_id) use ($obj) {
    $GLOBALS['obj'] = Pool::getIns();
    }
    );
    // 请求事件
    $http->on(
    'request', function (swoole_http_request $request, swoole_http_response $response) use
    ($http) {
    $row = $GLOBALS['obj']->findAll("select * from tt_article");
    $html = json_encode($row, JSON_UNESCAPED_UNICODE);
    $response->header('server', 'wuchen');
    $response->header('Content-Type', 'application/json;charset=utf-8');
    $response->end($html);
    }
    );
    // 启动服务
    $http->start();

    命令行执行脚本

    mysql中查看

  • 相关阅读:
    ZOJ 1002 Fire Net
    Uva 12889 One-Two-Three
    URAL 1881 Long problem statement
    URAL 1880 Psych Up's Eigenvalues
    URAL 1877 Bicycle Codes
    URAL 1876 Centipede's Morning
    URAL 1873. GOV Chronicles
    Uva 839 Not so Mobile
    Uva 679 Dropping Balls
    An ac a day,keep wa away
  • 原文地址:https://www.cnblogs.com/qiguaideta/p/11548862.html
Copyright © 2011-2022 走看看