Home > Backend Development > PHP Problem > How to use database connection pool in PHP?

How to use database connection pool in PHP?

慕斯
Release: 2023-03-10 20:56:02
forward
2882 people have browsed it

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 for each user 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. Therefore, this article will lead you to understand how PHP uses database connection pooling?

Related recommendations: What is the search algorithm in PHP array? How to find it?

xml

As a highly available structured language, XML is really concise and comprehensive as a configuration file. Although compared to recent leaders such as YAML and JSON in the configuration file world, the proportion of valid data may be 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

The first time I used this simple method, I was really a little depressed.

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

As a result, when using a 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 TAG information.

The last accidental test was to open the source code of the web page and found that this function did read all the information of 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 for each user 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

When there are too many applications, the request is rejected

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

How to use database connection pool in PHP?

#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.

How to use database connection pool in PHP?

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.
How to use database connection pool in PHP?

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.

Related learning video sharing: php video tutorial

The above is the detailed content of How to use database connection pool in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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