一、Java中数据库连接池的基本介绍
二、数据库连接池技术的优点
1. 资源重用
由于数据库连接得以重用,避免了频繁创建,释放连接引起的大量性能开销。在减少系统消耗的基础上,另一方面也增加了系统运行环境的平稳性。
2. 更快的系统反应速度
数据库连接池在初始化过程中,往往已经创建了若干数据库连接置于连接池中备用。此时连接的初始化工作均已完成。对于业务请求处理而言,直接利用现有可用连接,避免了数据库连接初始化和释放过程的时间开销,从而减少了系统的响应时间。
3. 新的资源分配手段
对于多应用共享同一数据库的系统而言,可在应用层通过数据库连接池的配置,实现某一应用最大可用数据库连接数的限制,避免某一应用独占所有的数据库资源。
4. 统一的连接管理,避免数据库连接泄漏
在较为完善的数据库连接池实现中,可根据预先的占用超时设定,强制回收被占用连接,从而避免了常规数据库连接操作中可能出现的资源泄露。
三、数据库连接池的种类
1.spring自带的DriverManagerDataSource数据源
<bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName"><value>com.jdbc.mysql.Driver</value></property><property name="url"><value>jdbc:mysql://localhost:3306/checkexdb?characterEncoding=utf8</value></property><property name="username"><value>test</value></property><property name="password"><value>test</value></property></bean>
Spring本身提供了一个简单的数据源实现类DriverManagerDataSource ,它位于org.springframework.jdbc.datasource包中。这个类实现了javax.sql.DataSource接口,但它并没有提供池化连接的机制,每次调用getConnection()获取新连接时,只是简单地创建一个新的连接。因此,这个数据源类比较适合在单元测试或简单的独立应用中使用,因为它不需要额外的依赖类。
下面是DriverManagerDataSource的简单使用:当然,我们也可以通过上面配置的方式直接使用DriverManagerDataSource。
DriverManagerDataSource ds = new DriverManagerDataSource ();ds.setDriverClassName("com.mysql.jdbc.Driver");ds.setUrl("jdbc:mysql://localhost:3306/checkexdb?characterEncoding=utf8");ds.setUsername("test");ds.setPassword("test");Connection actualCon = ds.getConnection();
2.DBCP数据源
Spring在第三方依赖包中包含了两个数据源的实现类包,其一是Apache的DBCP,其二是 C3P0。可以在Spring配置文件中利用这两者中任何一个配置数据源。
DBCP类包位于
下面是使用DBCP配置MySql数据源的配置片断:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3309/Summer" /><property name="username" value="root" /><property name="password" value="1234" /></bean>
BasicDataSource提供了close()方法关闭数据源,所以必须设定destroy-method=”close”属性, 以便Spring容器关闭时,数据源能够正常关闭。除以上必须的数据源属性外,还有一些常用的属性:
- defaultAutoCommit:设置从数据源中返回的连接是否采用自动提交机制,默认值为 true;
 - defaultReadOnly:设置数据源是否仅能执行只读操作, 默认值为 false;
 - maxActive:最大连接数据库连接数,设置为0时,表示没有限制;
 - maxIdle:最大等待连接中的数量,设置为0时,表示没有限制;
 - maxWait:最大等待秒数,单位为毫秒, 超过时间会报出错误信息;
 - validationQuery:用于验证连接是否成功的查询SQL语句,SQL语句必须至少要返回一行数据, 如你可以简单地设置为:“select count(*) from user”;
 - removeAbandoned:是否自我中断,默认是 false ;
 - removeAbandonedTimeout:几秒后数据连接会自动断开,在removeAbandoned为true,提供该值;
 logAbandoned:是否记录中断事件, 默认为 false;
3.C3P0数据源
C3P0是一个开放源代码的JDBC数据源实现项目,它在lib目录中与Hibernate一起发布,实现了JDBC3和JDBC2扩展规范说明的 Connection 和Statement 池。C3P0类包位于
/lib/c3p0/c3p0-0.9.0.4.jar。下面是使用C3P0配置一个mysql数据源: <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close"><property name="driverClass" value="com.jdbc.mysql.Driver"/><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/checkexdb?characterEncoding=utf8"/><property name="username" value="admin"/><property name="password" value="1234"/></bean>
ComboPooledDataSource和BasicDataSource一样提供了一个用于关闭数据源的close()方法,这样我们就可以保证Spring容器关闭时数据源能够成功释放。
C3P0拥有比DBCP更丰富的配置属性,通过这些属性,可以对数据源进行各种有效的控制:acquireIncrement:当连接池中的连接用完时,C3P0一次性创建新连接的数目;
- acquireRetryAttempts:定义在从数据库获取新连接失败后重复尝试获取的次数,默认为30;
 - acquireRetryDelay:两次连接中间隔时间,单位毫秒,默认为1000;
 - autoCommitOnClose:连接关闭时默认将所有未提交的操作回滚。默认为false;
 - automaticTestTable: C3P0将建一张名为Test的空表,并使用其自带的查询语句进行测试。如果定义了这个参数,那么属性preferredTestQuery将被忽略。你 不能在这张Test表上进行任何操作,它将中为C3P0测试所用,默认为null;
 - breakAfterAcquireFailure:获取连接失败将会引起所有等待获取连接的线程抛出异常。但是数据源仍有效保留,并在下次调 用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试获取连接失败后该数据源将申明已断开并永久关闭。默认为 false;
 - checkoutTimeout:当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限期等待。单位毫秒,默认为0;
 - connectionTesterClassName: 通过实现ConnectionTester或QueryConnectionTester的类来测试连接,类名需设置为全限定名。默认为 com.mchange.v2.C3P0.impl.DefaultConnectionTester;
 - idleConnectionTestPeriod:隔多少秒检查所有连接池中的空闲连接,默认为0表示不检查;
 - initialPoolSize:初始化时创建的连接数,应在minPoolSize与maxPoolSize之间取值。默认为3;
 - maxIdleTime:最大空闲时间,超过空闲时间的连接将被丢弃。为0或负数则永不丢弃。默认为0;
 - maxPoolSize:连接池中保留的最大连接数。默认为15;
 - maxStatements:JDBC的标准参数,用以控制数据源内加载的PreparedStatement数量。但由于预缓存的Statement属 于单个Connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素,如果maxStatements与 maxStatementsPerConnection均为0,则缓存被关闭。默认为0;
 - maxStatementsPerConnection:连接池内单个连接所拥有的最大缓存Statement数。默认为0;
 - numHelperThreads:C3P0是异步操作的,缓慢的JDBC操作通过帮助进程完成。扩展这些操作可以有效的提升性能,通过多线程实现多个操作同时被执行。默认为3;
 - preferredTestQuery:定义所有连接测试都执行的测试语句。在使用连接测试的情况下这个参数能显著提高测试速度。测试的表必须在初始数据源的时候就存在。默认为null;
 - propertyCycle: 用户修改系统配置参数执行前最多等待的秒数。默认为300;
 - testConnectionOnCheckout:因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的时候都 将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable
 - 等方法来提升连接测试的性能。默认为false;
 - testConnectionOnCheckin:如果设为true那么在取得连接的同时将校验连接的有效性。默认为false。
 
读配置文件的方式引用属性:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="location" value="/WEB-INF/jdbc.properties"/></bean><bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"><property name="driverClassName" value="${jdbc.driverClassName}" /><property name="url" value="${jdbc.url}" /><property name="username" value="${jdbc.username}" /><property name="password" value="${jdbc.password}" /></bean>
在jdbc.properties属性文件中定义属性值:
jdbc.driverClassName= com.mysql.jdbc.Driverjdbc.url= jdbc:mysql://localhost:3309/summerdbjdbc.username=rootjdbc.password=1234
提示 经常有开发者在${xxx}的前后不小心键入一些空格,这些空格字符将和变量合并后作为属性的值。如:的属性配置项,在前后都有空格,被解析后,username的值为“ 1234 ”,这将造成最终的错误,因此需要特别小心。
C3P0数据库连接池的使用,代码如下:
public class C3P0_ {//1.方式1:相关参数,在程序中指定user,url,password等@Testpublic void testC3P0_01() throws Exception {//1.创建一个数据源对象ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();//2.通过配置mysql.properties获取相关连接信息//通过Properties,获取相关配置文件的信息Properties properties = new Properties();properties.load(new FileInputStream("src\\mysql.properties"));//获取相关的值String user = properties.getProperty("user");String password = properties.getProperty("password");String driver = properties.getProperty("driver");String url = properties.getProperty("url");//给数据源comboPooledDataSource设置相关的参数//注意:连接管理是由comboPooledDataSource来管理comboPooledDataSource.setDriverClass(driver);comboPooledDataSource.setJdbcUrl(url);comboPooledDataSource.setUser(user);comboPooledDataSource.setPassword(password);//初始化连接数comboPooledDataSource.setInitialPoolSize(10);//设置最大连接数comboPooledDataSource.setMaxPoolSize(50);//测试连接池的效率,测试对mysql 5000次操作long start = System.currentTimeMillis();for (int i = 0; i < 5000; i++) {Connection connection = comboPooledDataSource.getConnection();//这个方法就是从DataSource接口实现的connection.close();}long end = System.currentTimeMillis();System.out.println("C3P0 5000次连接mysql耗时:" + (end - start));//C3P0 5000次连接mysql耗时:1038}//第二种方式,使用配置文件模板来完成//1.将c3p0提供的 拷贝到src目录下//2.该文件指定了连接数据库和连接池的相关参数@Testpublic void testC3P0_02() throws Exception {ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("ly_edu");//测试5000次连接mysqllong start=System.currentTimeMillis();System.out.println("开始执行");for (int i = 0; i < 5000; i++) {Connection connection = comboPooledDataSource.getConnection();connection.close();}long end=System.currentTimeMillis();System.out.println("C3P0 5000次连接mysql耗时:" + (end - start));//C3P0 5000次连接mysql耗时:1026}}
第二种方式需要使用配置模板来完成,将c3p0-config.xml拷贝到src目录下,就可以使用了,c3p0-config.xml代码如下:
<c3p0-config><!--数据库源名称代表连接池--><named-config name="ly_edu"><!-- 使用默认的配置读取连接池对象--><!-- 连接参数 --><property name="driverClass">com.mysql.cj.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://localhost:3306/db_ly?serverTimezone=GMT</property><property name="user">root</property><property name="password">123456</property><!-- 连接池参数 --><!--每次增长的连接数--><property name="acquireIncrement">5</property><!-- 初始连接数 --><property name="initialPoolSize">10</property><!--最小连接数--><property name="minPoolSize">5</property><!-- 最大连接数 --><property name="maxPoolSize">10</property><!--可连接的最多的命令对象数--><property name="maxStatements">5</property><!--每个连接对象可连接的最多的命令对象数--><property name="maxStatementsPerConnection">2</property></named-config></c3p0-config>
4.JNDI数据源
如果应用配置在高性能的应用服务器(如WebLogic或Websphere等)上,我们可能更希望使用应用服务器本身提供的数据源。应用服务器的数据源 使用JNDI开放调用者使用,Spring为此专门提供引用JNDI资源的JndiObjectFactoryBean类。下面是一个简单的配置例子:
<bean id="TerasolunaSampleDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"><property name="jndiName"><!-- Tomcat --><value>java:comp/env/jdbc/TerasolunaSummerDataSource</value><!-- Tomcat以外 --><!-- <value>jdbc/TerasolunaSummerDataSource</value> --></property></bean>
通过jndiName指定引用的JNDI数据源名称。
    Spring 2.0为获取J2EE资源提供了一个jee命名空间,通过jee命名空间,可以有效地简化J2EE资源的引用。下面是使用jee命名空间引用JNDI数据源的配置:
<beans xmlns=http://www.springframework.org/schema/beansxmlns:xsi=http://www.w3.org/2001/XMLSchema-instancexmlns:jee=http://www.springframework.org/schema/jeexsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsdhttp://www.springframework.org/schema/jeehttp://www.springframework.org/schema/jee/spring-jee-2.0.xsd"><jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/TerasolunaSummerDataSource"/></beans>
附在/META-INF/context.xml的DataSource链接情报:
<Context><Resourcename="jdbc/TerasolunaSummerDataSource"type="javax.sql.DataSource"driverClassName="org.postgresql.Driver"username="togodb"password="togo"url="jdbc:postgresql://127.0.0.1:5432/summerdb"maxIdle="2"maxWait="5000"maxActive="4"/></Context>
5.德鲁伊(Druid)数据库连接池
public class Druid_ {@Testpublic void testDruid() throws Exception {//1.加入Druid jar包//2.加入配置文件,将该文件拷贝到项目的src目录下//3.创建Properties对象,读取配置文件Properties properties = new Properties();properties.load(new FileInputStream("src\\druid.properties"));//4.创建一个指定参数的数据库连接池DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);long start =System.currentTimeMillis();for (int i = 0; i < 5000; i++) {Connection connection = dataSource.getConnection();connection.close();}long end =System.currentTimeMillis();System.out.println("Druid 5000次连接mysql耗时:" + (end - start));//Druid 5000次连接mysql耗时:3608}}
JDBCUtilsByDruid工具类代码如下:
//基于druid数据库连接池的工具类public class JDBCUtilsByDruid {private static DataSource ds;//在静态代码块完成 ds初始化static {try {Properties properties = new Properties();properties.load(new FileInputStream("src\\druid.properties"));ds = DruidDataSourceFactory.createDataSource(properties);} catch (Exception e) {e.printStackTrace();}}//编写getConnection方法public static Connection getConnection() throws SQLException {return ds.getConnection();}//关闭连接,在数据库连接池中,close不是真正的断掉连接//而是把使用的Connection对象放回到连接池public static void close(ResultSet resultSet, Statement statement, Connection connection) {try {if (resultSet != null) {resultSet.close();}if (statement != null) {statement.close();}if (connection != null) {connection.close();}} catch (SQLException e) {throw new RuntimeException(e);}}}
JDBCUtilsByDruid工具类的使用:
public class JDBCUtilsByDruid_Use {@Testpublic void testSelect() {Connection connection = null;String sql = "SELECT id,name,borndate FROM ACTOR WHERE id = ?";PreparedStatement preparedStatement = null;ResultSet resultSet = null;try {//1.得到连接connection = JDBCUtilsByDruid.getConnection();System.out.println(connection.getClass());//class com.alibaba.druid.pool.DruidPooledConnectionpreparedStatement = connection.prepareStatement(sql);preparedStatement.setInt(1, 2);//执行得到结果集resultSet = preparedStatement.executeQuery();while (resultSet.next()) {String name = resultSet.getString("name");int id = resultSet.getInt("id");Date borndate = resultSet.getDate("borndate");System.out.println(id + "\t" + name + "\t" + borndate);}} catch (Exception e) {e.printStackTrace();} finally {JDBCUtilsByDruid.close(resultSet, preparedStatement, connection);}}}

