PHP如何实现数据库连接池-PHP问题

资源魔 102 0

PHP若何完成数据库衔接池

起首界说一个类并申明一个属性作为衔接池子;而后正在结构办法中向池子进行填充衔接实例;最初再界说一个掏出办法以及放回办法,掏出时将衔接池最初一个衔接实例进行出栈并前往,放回时将衔接实例压入衔接池末栈便可。

实例代码:

<?php
namespace Db\Connect;

class Pool
{

  protected $size = 10;

  protected $connects = [];

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

  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['hostname'],
          $this->dbConf['username'],
          $this->dbConf['password'],
          $this->dbConf['dbname']
        );

        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 mysql php教程 php故障解决 php使用问题

抱歉,评论功能暂时关闭!