php 实现 连接池

参考配置修改:http://www.thinkphp.cn/topic/26541.html 
防止访问量过大,把连接数占满了

<?php

/**
 * @author xuleyan
 * @title mysql类
 */

class DbHelper{
    //连接池
    private $_pools = [];

    //连接池大小
    const POOLSIZE = 5;

    const USERNAME = "root";
    const PASSWORD = "root";
    const HOST = "127.0.0.1";
    const DB = "test";

    public function __construct()    
    {
        $db = self::DB;
        $username = self::USERNAME;
        $password = self::PASSWORD;
        $host = self::HOST;

        //持久化连接
        $presistent = array(PDO::ATTR_PERSISTENT => true);

        for ($i=0; $i < self::POOLSIZE; $i++) { 
            $connection = new PDO("mysql:dbname=$db;host=$host", $username, $password);
            // sleep(3);
            array_push($this->_pools, $connection);
        }
    }

    //从数据库连接池中获取一个数据库链接资源
    public function getConnection()
    {
        echo 'get' . count($this->_pools) . "<br>";
        if (count($this->_pools) > 0) {
            $one =  array_pop($this->_pools);
            echo 'getAfter' . count($this->_pools) . "<br>";
            return $one;
        } else {
            throw new ErrorException ( "<mark>数据库连接池中已无链接资源,请稍后重试!</mark>" );
        }
    }

    //将用完的数据库链接资源放回到数据库连接池
    public function release($conn)
    {
        echo 'release' . count($this->_pools) . "<br>";
        if (count($this->_pools) >= self::POOLSIZE) {
            throw new ErrorException ( "<mark>数据库连接池已满!</mark>" );
        } else {
            array_push($this->_pools, $conn);
            // $conn = null;
            echo 'releaseAfter' . count($this->_pools) . "<br>";
        }
    }

    public function query($sql)
    {
        try {
            $conn = $this->getConnection();
            $res = $conn->query($sql);
            $this->release($conn);
            return $res;
        } catch (ErrorException $e) {
            print 'error:' . $e->getMessage();
            die;
        }
    }

    public function queryAll($sql)
    {
        try {
            $conn = $this->getConnection();
            $sth = $conn->prepare($sql);
            $sth->execute();
            $result = $sth->fetchAll();
            return $result;
        } catch (PDOException $e) {
            print 'error:' . $e->getMessage();
            die;
        }
    }
}

在另外的文件这样调用

<?php 

require_once 'db.php';
$sql = 'select * from user';

$dbhelper = new DbHelper;
for ($i=0; $i < 10; $i++) { 
    $res = $dbhelper->query($sql);
    // var_dump($res) . PHP_EOL;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值