Home Backend Development PHP Tutorial C实现PHP的MySQL数据库连接池

C实现PHP的MySQL数据库连接池

Jun 23, 2016 pm 01:17 PM

一、导语

连接池在JAVA中应用的很广泛,而在PHP中很少使用。

以Mysql为例,JAVA中使用连接池的原因之一是避免重复新建、释放连接资源带来的开销。而在PHP中都是直连,因为这部分开销对于C API而言性能上是没有问题的。

那么既然PHP直连已经没有性能问题,那为何还要多次一举开发mysql的数据库连接池扩展呢?因为根本的目的是在于理解PHP的TS(Tthread Safe线程安全)与NTS(Not Thread Safe非线程安全)运行模式,而并非数据库连接池这个功能。

二、原理

连接池的基本思想是在系统加载时,初始化默认数量的连接对象存储在内存中,当有客户端需要访问数据库时,根据场景选择是分配、新建、等待、失败返回连接对象。使用完毕之后,连接将被重新放置回连接池中等待下一个请求的再分配,而不是释放内存。

连接池中连接的建立、释放都由连接池自身来管理,同时可以通过设置初始化最小连接数、最大连接数、最大空闲时间等来配置连接池。

注:在此扩展中,提供了最小连接数(min_connection)、最大连接数(max_connection)的设置

三、实现思路

1.定义全局数组变量dbpools

dbpools中的元素类型为

struct _mysql_node{     MYSQL *mysql;   //连接资源句柄     int is_used;    //标记是否被占用     int result_id;  //记录my_mysql_query的查询结果集} mysql_node;
Copy after login

2.通过获取配置文件中设置的min_connection初始化dbpools

3.定义全局变量db_pools_length(目前拥有链接数)、db_pools_use_length(目前被使用的链接数),通过这两个值来确定分配资源的情景

注:正因为使用全局变量实现连接池,通过修改全局变量的状态来选择资源连接,决定了该扩展必须运行在共享全局变量的ZTS(Zend Thread Safe)线程安全模式下。(例如IIS或Apache MPM Worker模式)

如果希望支持多进程,可以通过进程间通信来设置全局变量,实现线程池。

实现思路图:

图片:1.jpg

四、理解PHP线程与进程的工作模式

(一)多进程工作模式

PHP的多进程工作模式以Apache apxs举例。

apache启动时,会fork出N个子进程用来等待接受处理客户端的请求。进程之间相互隔离,全局变量也无法直接访问(可以通过进程间通信访问)。这样的好处是能够保证PHP环境的长时间稳定,

即使有部分进程因内存泄漏而崩溃也不会影响其他进程。由于PHP相当于粘合剂,它实际相当于集合多个库的API,例如集合了libcurl、libmemcache、libzip等,要保证所有的库都正常运行是比较困难的。

那么为了保证PHP的高可靠性,这种多进程的模式就是首选。

图片:2.jpg

(二)多线程工作模式

PHP的多线程工作模式以IIS举例。

这种模式下,只有一个进程在后台运行着,所有请求都是通过这一个进程来完成。只是在处理每个请求时,会创建独立的线程来处理。

正是因为使用多线程这种模式,可以直接访问全局变量得以方便的实现数据库连接池。

图片:3.jpg

六、使用此扩展前提条件与方法

1.widnwos下IIS Server或Apache多线程模式,php5.3.*

2.修改php.ini,添加

[my_mysql]

my_mysql.host = localhost

my_mysql.user = root

my_mysql.password =

my_mysql.port = 3306

my_mysql.max_connection = 200 //最大连接数

my_mysql.min_connection = 100 //默认最小连接数

看到这里的配置,能看出来这个数据库连接池扩展没有实现多数据源的连接池。因为目的不在连接池本身,所以也没有特地去写多数据源的功能。

3.修改php.ini,添加

extension=php_my_mysql.dll

4.重启apache server

七、相关下载

扩展dll下载: php_my_mysql.dll

源码下载: http://yunpan.cn/QWmEN8PuuRVYN

扩展测试结果

测试配置:

[my_mysql]

my_mysql.max_connection = 2 //最大连接数

my_mysql.min_connection = 1 //默认最小连接数

使用三个浏览器,运行下列测试脚本:

<?php/*** 从数据库连接池中取得一个链接资源* 可能产生如下情景* 1.如果有空闲连接则直接返回链接资源* 2.如果没有空闲连接,并且连接数没有超过最大连接数,则扩充连接池并返回新建的链接资源* 3.如果没有空闲连接同时已经是最大连接数,则进入等待,超过1.5s仍没有空闲资源则超时返回NULL.** 失败返回NULL*/$db = my_mysql_get_conn();   if($db === false){     exit('dbpool is exhushed.');}   /*** 选择数据库* @param resource $db* @param string $db_name 数据库名称*/my_mysql_select_db($db, 'test');   /*** ping数据库*/my_mysql_ping($db);   /*** 执行SQL语句,可以执行INSERT、SHOW、SELECT、UPDATE、DELETE等语句* @param  resource $db* @param string $sql SQL*/my_mysql_query($db, "INSERT INTO test VALUES(id, 'dbpool', 'test dbpool')");   // 获取上一条INSERT语句返回的自增ID$id = my_mysql_get_insert_id($db);echo $id;   $result = my_mysql_query($db, "SELECT * FROM test");   /*** 将查询结果转换为二维数组* @param resource $db*/$arr = my_mysql_fetch_assoc($result);   print_r($arr);   sleep(3);   var_dump($db);//sleep之后,必须输出$db,否则会因为PHP的解析优化,sleep过程中已经将$db释放,就没有办法测试连接被占用的情况。
Copy after login

测试结果图:

图片:4.jpg

返回warning的,是由于连接池资源被占用完,会进入等待。如果1.5s仍没有等待到资源,则返回dbpool is exhushed。
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles