Detailed analysis of PHP implementation of database connection pool

黄舟
Release: 2023-03-06 14:24:01
Original
3109 people have browsed it

Summary

In the past, PHP code was always written in a script-oriented process, so to a large extent, it was neither standardized nor safe, nor easy to maintain. In order to reuse code, I plan to write a set of my own tool library, so that it can be easily used when writing projects in the future.

What we are going to implement today is a database connection pool, which is implemented in the form of a configuration file.

xml

As a highly available structured language, XML is really concise and comprehensive as a configuration file. Although compared to the recent leaders in the configuration file world such as YAML and JSON, it may The proportion of valid data is relatively small, but this redundancy has its value.

Basically, you can know its functions after reading the xml nodes. This is why large projects use XML as configuration files.

Redundancy can be tolerated, but it cannot bring any ambiguity or maintenance difficulties.

In PHP, using XML files will be a pleasing thing, although compared to Java programs, this is not the case. But compared to Python processing, PHP programs are not so elegant.

Reading the configuration file

Reading the configuration file actually means reading the file and then packaging it. The following two methods are commonly used by me.

Easy method

When I used this simple method for the first time, I was really a little depressed.

$content = file_get_contents("filename.xml");
echo $content;
Copy after login

As a result, when using the browser to access the php file for testing, only the content of the xml was displayed, but the node information was not displayed at all.

Then I checked the help documentation and found that the result returned by this function is undoubtedly a string. Then vardump also proved this. So I didn't think much about it, thinking that this method could automatically filter out the XML tag information.

As a final accidental test, I opened the source code of the web page and found that this function did read all the information in the XML, but it was automatically parsed by the browser when it was displayed on the browser. So only the relevant content parts can be seen.

Conventional method

The conventional method is to read the file step by step. The rest is consistent with the above plan.

// 读取配置文件内容
            $handle = fopen("filepath", "r");            
            $content = fread($handle, filesize("filepath"));
Copy after login

PHP parses XML

The above two kinds of reading files are actually prepared for PHP to parse XML. There are many blogs about the way PHP parses XML. There are many ways, such as simplexml, XMLReader, DOM and so on. But for smaller xml configuration files, simplexml is enough.

Configuration file

<?xml version="1.0" encoding="UTF-8" ?><mysql>
    <!-- 为防止出现意外,请按照此标准顺序书写.其实也无所谓了 -->
    <host>localhost</host>
    <user>root</user>
    <password>123456</password>
    <db>test</db>
    <port>3306</port></mysql>
Copy after login

Analysis

<?php/**
 * 作为解析XML配置文件必备工具
 */class XMLUtil {
    public static $dbconfigpath = "./db.config.xml";    
    public static function getDBConfiguration() {
        $dbconfig = array ();        
        try {            
        // 读取配置文件内容
            $handle = fopen(self::$dbconfigpath, "r");            
            $content = fread($handle, filesize(self::$dbconfigpath));            
            // 获取xml文档根节点,进而获取相关的数据库信息
            $mysql = simplexml_load_string($content);            
            // 将获取到的xml节点信息赋值给关联数组,方便接下来的方法调用
            $dbconfig[&#39;host&#39;] = $mysql->host;            
            $dbconfig[&#39;user&#39;] = $mysql->user;            
            $dbconfig[&#39;password&#39;] = $mysql->password;            
            $dbconfig[&#39;db&#39;] = $mysql->db;            
            $dbconfig[&#39;port&#39;] = $mysql->port;            
            // 将配置信息以关联数组的形式返回
            return $dbconfig;
        } catch ( Exception $e ) {            
        throw new RuntimeException ( "<mark>读取数据库配置文件信息出错!</mark><br />" );
        }        return $dbconfig;
    }
}
Copy after login

Database connection pool

For PHP programs, optimization never ends. The database connection pool plays an optimization role to a certain extent. This eliminates the need to apply for link resources from the database every time a user makes a request. Instead, it is returned through the link in the existing database connection pool, which is a big improvement in terms of time and efficiency.

So, here is a simple simulation of the implementation of the database connection pool. The core is to maintain a "pool".

Take it from the pool, use it, and return it to the pool.

<?php/**x
 *  PHP中的数据库 工具类设计
 *  郭璞
 *  2016年12月23日
 *  
 **/class DbHelper {    
 private $dbconfig;    
 private $dbpool;    
 public $poolsize;    
 public function __construct($poolsize = 20) {        
 if (! file_exists ( "./utils.php" )) {            
 throw new RuntimeException ( "<mark>utils.php文件丢失,无法进行配置文件的初始化操作!</mark><br />" );
        }else {
            require &#39;./utils.php&#39;;
        }        // 初始化 配置文件信息
        $this->dbconfig = XMLUtil::getDBConfiguration ();        
        // 准备好数据库连接池“伪队列”
        $this->poolsize = $poolsize;
        $this->dbpool = array ();        
        for($index = 1; $index <= $this->poolsize; $index ++) {
            $conn = mysqli_connect ( $this->dbconfig [&#39;host&#39;], $this->dbconfig [&#39;user&#39;], $this->dbconfig [&#39;password&#39;], $this->dbconfig [&#39;db&#39;] ) 
            or die ( "<mark>连接数据库失败!</mark><br />" );
            array_push ( $this->dbpool, $conn );
        }
    }    /**
     * 从数据库连接池中获取一个数据库链接资源
     *
     * @throws ErrorException
     * @return mixed
     */
    public function getConn() {        
    if (count ( $this->dbpool ) <= 0) {            
    throw new ErrorException ( "<mark>数据库连接池中已无链接资源,请稍后重试!</mark>" );
        } else {            
        return array_pop ( $this->dbpool );
        }
    }    /**
     * 将用完的数据库链接资源放回到数据库连接池
     *
     * @param unknown $conn            
     * @throws ErrorException
     */
    public function release($conn) {        
    if (count ( $this->dbpool ) >= $this->poolsize) {            
    throw new ErrorException ( "<mark>数据库连接池已满</mark><br />" );
        } else {
            array_push ( $this->dbpool, $conn );
        }
    }
}
Copy after login

Test

Reject the request when there are too many applications

When the number of applications for database connections is less than 20, the program directly obtains it from the database connection pool.

Detailed analysis of PHP implementation of database connection pool

#When the requested database link resource is greater than the upper limit of the database connection pool, it will not be provided. and prompt an exception.

Detailed analysis of PHP implementation of database connection pool

Refuse to put in when full

When the database connection pool is full, if you want to return to the customized database link resource, it is not supported. , and an error message is reported.
Detailed analysis of PHP implementation of database connection pool

Summary

To review, this experiment mainly designed and implemented a simple database connection pool from an object-oriented perspective. It plays a role in optimizing PHP code to a certain extent.

In addition, simplexml is simply used to parse XML files and perform common file reading operations.

The above is the detailed content of Detailed analysis of PHP implementation of database connection pool. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template