DBCP(DataBase Connection Pool)数据库连接池,是Java数据库连接池的一种,由Apache开发,也是 tomcat 使用的连接池组件。
通过数据库连接池,可以让程序自动管理数据库连接的释放和断开。
由于建立数据库连接是一种非常耗时、耗资源的行为,所以通过连接池预先同数据库建立一些连接,放在内存中,应用程序需要建立数据库连接时直接到连接池中申请一个就行,使用完毕后再归还到连接池中。
1. DBCP所依赖的jar包
commons-dbcp2-2.1.1.jar
commons-logging-1.2.jar
commons-pool2-2.4.2.jar
maven
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
2. DBCP的properties配置文件
########DBCP配置文件##########
#驱动名
driverClassName=com.mysql.jdbc.Driver
#url
url=jdbc:mysql://127.0.0.1:3306/mydb
#用户名
username=sa
#密码
password=123456
#初试连接数
initialSize=30
#最大活跃数
maxTotal=30
#最大idle数
maxIdle=10
#最小idle数
minIdle=5
#最长等待时间(毫秒)
maxWaitMillis=1000
#程序中的连接不使用后是否被连接池回收(该版本要使用removeAbandonedOnMaintenance和removeAbandonedOnBorrow)
#removeAbandoned=true
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true
#连接在所指定的秒数内未使用才会被删除(秒)(为配合测试程序才配置为1秒)
removeAbandonedTimeout=1
#建立连接时的附加参数,如果指定的编码不一致数据库中会出现乱码(MySQL)
connectionProperties=useUnicode=true;characterEncoding=utf8
3. 获取DataSource对象
private static Properties properties = new Properties();
private static DataSource dataSource;
//加载DBCP配置文件
static{
try{
FileInputStream is = new FileInputStream("config/dbcp.properties");
properties.load(is);
}catch(IOException e){
e.printStackTrace();
}
try{
dataSource = BasicDataSourceFactory.createDataSource(properties);
}catch(Exception e){
e.printStackTrace();
}
}
4. 获取Connection对象
//从连接池中获取一个连接
public static 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;
}
5. DBCP配置的详细属性
-
driverClassName=com.mysql.jdbc.Driver // 驱动加载
-
url=jdbc:mysql://localhost/db_student // 驱动注册
-
username=root //要连接的数据库用户名
-
password=root // 要连接的数据库密码
-
defaultAutoCommit=true:// 设置是否自动提交,默认为true
-
defaultReadOnly=false: // 是否为只读 默认为false
-
defaultTransactionIsolation=3:// 设置数据库的事务隔离级别默认为1,READ_UNCOMMITTED,推荐设置为3
-
initialSize=10: // 初始化数据池拥有的连接数量
-
maxActive=20: /池中最多可容纳的活着的连接数量,当达到这个数量不在创建连接
-
maxIdle=20: // 最大空闲等待,也就是连接等待队列超过这个值会自动回收未使用的连接,直到达到20
-
minIdle=5: // 最小空闲等待 ,数据池中最少保持的连接
-
maxWait=10000 // 最大等待时间,超过这个时间等待队列中的连接就会失效
-
testOnBorrow=true //从池中取出连接时完成校验 ,验证不通过销毁这个connection,默认为true,
-
testOnReturn=false //放入池中时完成校验,默认我fasle
-
validationQuery=select 1 // 校验语句,必须是查询语句,至少查询一列,设置了它onBorrow才会生效
-
validationQueryTimeout=1 // 校验查询时长,如果超过,认为校验失败
-
testWhileIdle=false // 清除一个连接时是否需要校验
-
timeBetweenEvictionRunsMillis=1 // DBCP默认有个回收器Eviction,这个为设置他的回收时间周期
-
numTestsPerEvictionRun=3 // Eviction在运行时一次处理几个连接
-
poolPreparedStatements=true //是否缓存PreparedStatements
-
maxOpenPreparedStatements=1 // 缓存PreparedStatements的最大个数