druid源码分析—DruidDataSource的基本分析(一)
前言
在Java程序中操作数据库(JDBC),必须先获得一个连接(Connection)。
但每次操作完毕后,连接就要被释放。下一次连接又得重新创建,再释放,非常的浪费资源。
为了避免资源浪费就有了一个想法,我们可以创建一个连接池当我需要的时候,直接从池里获取。
什么是Druid?
Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。
DruidDataSource构造方法(constructor)
public DruidDataSource(){
this(false);
}
public DruidDataSource(boolean fairLock){
//创建了重入锁并设置了为非公平锁。
super(fairLock);
//初始化复制Properties中的参数
configFromPropety(System.getProperties());
}
在super(fairLock)
方法中我们知道了三个关于并发包的参数,后续关于并发应该会使用到,先记录下来。参数如下:lock
、notEmpty
、empty
protected ReentrantLock lock;
protected Condition notEmpty;
protected Condition empty;
获取连接(getConnection)
返回DruidPooledConnection
/**
* 获取连接
* @return DruidPooledConnection Druid连接池中的连接
* @throws SQLException
*/
@Override
public DruidPooledConnection getConnection() throws SQLException {
return getConnection(maxWait);
}
public DruidPooledConnection getConnection(long maxWaitMillis) throws SQLException {
//初始化加载仅加载一次
init();
if (filters.size() > 0) {
FilterChainImpl filterChain = new FilterChainImpl(this);
return filterChain.dataSource_connect(this, maxWaitMillis);
} else {
//默认获取连接方法
return getConnectionDirect(maxWaitMillis);
}
}
//DEFAULT_MAX_WAIT = -1 , maxWait 最大等待时间?
protected volatile long maxWait = DEFAULT_MAX_WAIT;
默认获取连接方法(getConnectionDirect)![getConnectionDirect](https://i-blog.csdnimg.cn/blog_migrate/2c2a304c292f270c668746a6da857d4f.png)
getConnectionDirect
代码中主要是循环获取连接。主要分为三块代码:
getConnectionInternal(maxWaitMillis)
获取连接的实例类,获取连接超时会进入catch
,在参数notFullTimeoutRetryCnt
做累加,并进行重试继续获取连接,一旦重试次数超过this.notFullTimeoutRetryCount
则直接抛出当前异常。testOnBorrow
,主要是为了对连接进行校验,默认值是false
,
true
时,会对连接进行连接校验,比较的浪费资源。(后续再深挖)
false
时,会判断连接是否处于关闭,如果关闭则continue
,再测试连接是否处于空闲状态,如果处于非空闲状态,则continue
removeAbandoned
顾名思义就是移除废弃的连接。
今日总结
今日主要是看了constructor
、getConnection
、getConnectionDirect
这三个方法。
constructor
中主要是创建锁对System.getProperties()
参数进行基本的加载。
getConnection
中主要分为三部分、init初始化数据源,有过滤器的情况下获取连接,无过滤器获取连接。
getConnectionDirect
中也主要分为三部分,分别为获取连接、对连接进行校验、移出废弃的连接。
明日主要分析getConnectionDirect
方法下的getConnectionInternal
方法,并记录参数。