数据库连接池简介

本文主要介绍数据库连接池的相关知识。

1. 概述

1.1 what

In software engineering, a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required. 

1.2 why

Connection pools are used to enhance the performance of executing commands on a database. 

Opening and maintaining a database connection for each user, especially requests made to a dynamic database-driven website application, is costly and wastes resources. In connection pooling, after a connection is created, it is placed in the pool and it is used again so that a new connection does not have to be established. If all the connections are being used, a new connection is made and is added to the pool. Connection pooling also cuts down on the amount of time a user must wait to establish a connection to the database.

1.3 how

本节介绍数据库连接池是如何工作的。

在系统初始化阶段,创建一定数量的数据库连接对象(connection)),并将这些对象存储在连接池(connection pool)中(对应某种类型的容器,如 list )。当有数据库连接请求时,就从连接池中取出一个数据库连接;如果此时连接池中的数据库连接已经用完了,并且当前的连接数还没有达到连接池定义的最大连接数时,则可再创建一个新的连接,而如果当前的连接数已达到最大连接数时,就要等待其他连接请求释放连接、连接池中存在空闲连接时才能获取连接。当一个连接请求使用完连接时,必须将该连接放回到连接池中,这样不同的数据库访问请求就可以共享连接池中的连接了。通过重复使用连接池中的数据库连接,可以避免前面提到的频繁建立连接的缺点,提高了数据库的性能。

现在,我们把上述描述拆分为以下几步,便于更清晰地认识数据库连接池的工作原理:

一、当服务启动时,建立一个数据库连接池对象;

二、初始化一定数量的数据库连接,放入连接池对象的容器中;

三、当有数据库访问请求时,直接从连接池的容器中获取一个连接,这里连接池中是否仍有空闲连接,存在以下三种情况:

  • 当容器中的还有空闲连接时,则分配给数据库访问请求者一个连接
  • 当容器中没有空闲连接时,并且当前已建立的连接数没有达到连接池定义的最大连接数时,则需要创建一个新的数据库连接,并将该连接分配给数据库访问请求者
  • 当容器中的没有空闲连接,并且当前已建立的连接数达到了连接池定义的最大连接数时,则当前数据库访问请求者就需要等待其他访问请求者释放连接,然后再从连接池中获取连接

四、当数据库访问请求使用完连接后,需要将连接放回到连接池中;

五、当服务停止时,需要先释放数据库连接池中的所有数据库连接,然后再释放数据库连接池对象。

以上内容就是数据库连接池的主要工作原理。

关于数据库连接池的具体实现方法,请点击此处

猜你喜欢

转载自blog.csdn.net/liitdar/article/details/80539534