首页  >  文章  >  后端开发  >  PHP如何实现数据库连接池

PHP如何实现数据库连接池

Guanhui
Guanhui原创
2020-05-14 13:08:495070浏览

PHP如何实现数据库连接池

PHP如何实现数据库连接池

首先定义一个类并声明一个属性作为连接池子;然后在构造方法中向池子进行填充连接实例;最后再定义一个取出方法和放回方法,取出时将连接池最后一个连接实例进行出栈并返回,放回时将连接实例压入连接池末栈即可。

实例代码:

<?php
namespace Db\Connect;

class Pool
{

  protected $size = 10;

  protected $connects = [];

  protected $dbConf = [
    &#39;hostname&#39; => &#39;127.0.0.1&#39;,
    &#39;username&#39; => &#39;root&#39;,
    &#39;password&#39; => &#39;123456&#39;,
    &#39;dbname&#39; => &#39;dbname&#39;
  ];

  public function __construct($size = 10, $dbConf = [])
  {
    $this->size = $size;

    $this->dbdbConf = array_merge($this->dbdbConf, $dbdbConf);

    for($index = 1; $index <= $this->size; $index ++) {

        $connect = mysqli_connect(
          $this->dbConf[&#39;hostname&#39;],
          $this->dbConf[&#39;username&#39;],
          $this->dbConf[&#39;password&#39;],
          $this->dbConf[&#39;dbname&#39;]
        );

        array_push($this->connects, $connect);
    }
  }

  public function getConnect()
  {
    if (count($this->connects) <= 0) {
        throw new \ErrorException( "数据库连接池中已无链接资源,请稍后重试!" );
    } else {
        return array_pop($this->connects);
    }

  }

  public function release($connect)
  {
    if (count($this->connects) >= $this->size) {
      throw new \ErrorException("数据库连接池已满");
    } else {
      array_push($this->connects, $connect);
    }
  }

}

推荐教程:《PHP教程

以上是PHP如何实现数据库连接池的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn