java [30] dbcp连接池的使用

前言

在之前的文章中,我们学习了如何使用原生的JDBC连接操作数据库,如果对使用原生JDBC操作数据库比较熟的读者,可能会注意到这样一个问题,就是每次需要使用的时候,都需要获取一个Connection,然后通过Connection来获得相应的PreparedStatement,进而操作数据库。当每次创建一个Connection的时候,所需要消耗的资源是比较大的,但是如果使用单例的Connection,又无法提高性能,这个时候问题的就出现了,一方面我们希望减少频繁创建Connection来减少资源的消耗,从而提高性能,另一方面,又希望能够在并发量比较大的时候,能够有多个Connection并发操作,从而提高性能。解决这个问题的一个比较好的做法就是使用池化技术,也就是通过创建数据库连接池来管理Connection,每次使用完一个Connection之后,便将其归还给池,而不是关闭,当再次需要获取的时候,直接从池中拿出,这样就减少了很大的创建、销毁Connection的消耗了,在Java中,目前使用得比较多的数据库连接池技术有两种,分别是DBCP以及C3P0。

DBCP的简单介绍

DBCP是Apache软件基金会组织下的一个开源的数据库连接池的实现,全称是DataBase Connection Pool,tomcat默认使用的连接池组件,单独使用时需要两个组件commons-dbcp.jar,commons-pool.jar。

使用步骤:

1.导包

2.写配置文件:

dbcp.propertities

######## DBCP配置文件 ##########
 # 驱动名
 driverClassName=com.mysql.cj.jdbc.Driver
 # url
 url=jdbc:mysql://192.168.11.138:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
 # 用户名
 username=root
 # 密码
 password=root
 # 初始连接数
 initialSize=3
 # 最大活跃数
 maxTotal=5
 # 最大空闲数
 maxIdle=5
 # 最小空闲数
 minIdle=3
 # 最长等待时间(毫秒)
 maxWaitMillis=1000
 # 程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
 # removeAbandoned=true
 #removeAbandonedOnMaintenance=true
 #removeAbandonedOnBorrow=true
 # 连接在所指定的秒数内未使用才会被删除(秒)
 #removeAbandonedTimeout=100

3.在代码中如何使用:

DBCPUtils

package datasource;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSourceFactory;

public class DBCPUtils {
	private static Properties properties = new Properties();
    private static DataSource dataSource;
    //加载DBCP配置文件
    static{
       try{
          //注意这里需要使用绝对路径
          //FileInputStream is = new FileInputStream("src/dbcp.properties"); 
    	   //这种方法不需要指定路径
    	   InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("dbcp.properties");
          properties.load(is);
       //获取数据源对象
           dataSource = BasicDataSourceFactory.createDataSource(properties);
       }catch(Exception e){
           throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件");
       }
    }
    //取出数据源
    public static DataSource getDataSource() {
    	return dataSource;
    }
    
    //从连接池中获取一个连接
    public static synchronized Connection getConnection(){
       Connection connection = null;
       try{
            connection = dataSource.getConnection();
        }catch(SQLException e){
            e.printStackTrace();
        }
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
}

然后就能直接获取connection操纵数据库了。

测试下:

package com.us.test;

import java.sql.Connection;
import java.sql.SQLException;

import datasource.DBCPUtils;

public class dbcptest {
	public static void main(String[] args) throws SQLException {
		Connection conn = null;
		for (int i=0;i<10;i++) {
			conn = DBCPUtils.getConnection();
			System.out.println(conn);
			System.out.println(conn.getClass().getName());
			conn.close();
		}
	}
}

输出:

64830413, URL=jdbc:mysql://192.168.11.138:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT, [email protected], MySQL Connector/J
org.apache.commons.dbcp2.PoolingDataSource$PoolGuardConnectionWrapper
157456214, URL=jdbc:mysql://192.168.11.138:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT, [email protected], MySQL Connector/J
org.apache.commons.dbcp2.PoolingDataSource$PoolGuardConnectionWrapper
1935365522, URL=jdbc:mysql://192.168.11.138:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT, [email protected], MySQL Connector/J
org.apache.commons.dbcp2.PoolingDataSource$PoolGuardConnectionWrapper

猜你喜欢

转载自blog.csdn.net/qq_38125626/article/details/82216878