Druid是如何初始化数据源的
上一篇文章介绍了DruidDataSource的构造方法,但是构造方法并没有初始化连接池,那么Druid是在什么时候初始化了连接池呢
// 构造方法看上篇
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/druid");
dataSource.setUsername("root");
dataSource.setPassword("12345678");
// 当调用了dataSource.getConnection方法时 进行初始化
Connection conn = dataSource.getConnection();
创建连接池入口 getConnection()
构造完DruidDataSource方法后,调用dataSource.getConnection() 进入真正初始化connection pool的流程
public DruidPooledConnection getConnection(long maxWaitMillis) throws SQLException {
// 初始化的核心
init();
// 对filter的加载
if (filters.size() > 0) {
FilterChainImpl filterChain = new FilterChainImpl(this);
return filterChain.dataSource_connect(this, maxWaitMillis);
} else {
return getConnectionDirect(maxWaitMillis);
}
}
核心方法 init()
public void init() throws SQLException {
// 不能重复初始化 保证只有一个实例
if (inited) {
return;
}
// bug fixed for dead lock, for issue #2980
// 之前老版本的一个bug 多个线程初始化datasource,这里把DruidDriver的初始化前置了
DruidDriver.getInstance();
// 非公平的ReentrantLock 可中断锁
final ReentrantLock lock = this.lock;
try {
// 获取不到则终止
lock.lockInterruptibly();
} catch (InterruptedException e) {
throw new SQLException("interrupt", e);
}
// 再判断是否初始化,避免程序中多个datasource初始化
boolean init = false;
try {
if (inited) {
return;
}
initStackTrace = Utils.toString(Thread.currentThread().getStackTrace());
// 原子自增生成一个id 从0 -> 1,如果只有一个datasource不会进去
this.id = DruidDriver.createDataSourceId();
if (this.id > 1) {
long delta = (this.id - 1) * 100000;
this.connectionIdSeedUpdater.addAndGet(this, delta);
this.statementIdSeedUpdater.addAndGet(this, delta);
this.resultSetIdSeedUpdater.addAndGet(this, delta);
this.transactionIdSeedUpdater.addAndGet(this, delta);
}
if (this.jdbcUrl != null) {
this.jdbcUrl = this.jdbcUrl.trim();
// todo initFromWrapDriverUrl
initFromWrapDriverUrl();
}
// 初始化wall log stats等过滤器
for (Filter filter : filters) {
filter.init(this);
}
// 获取db的类型 mock mysql oceanbase ads等
if (this.dbTypeName == null || this.dbTypeName.length() == 0) {
this.dbTypeName = JdbcUtils.getDbType(jdbcUrl, null);
}
DbType dbType = DbType.of(this.dbTypeName);
if (dbType == DbType.mysql
|| dbType == DbType.mariadb
|| dbType == DbType.oceanbase
|| dbType == DbType.ads) {
boolean cacheServerConfigurationSet = false;
if (this.connectProperties.containsKey("cacheServerConfiguration")) {
cacheServerConfigurationSet = true;
} else if (this.jdbcUrl.indexOf("cacheServerConfiguration") != -1) {
cacheServerConfigurationSet = true;
}
if (cacheServerConfigurationSet) {
this.connectProperties.put("cacheServerConfiguration", "true");
}
}
if (maxActive <= 0) {
throw new IllegalArgumentException("illegal maxActive " + maxActive);
}
if (maxActive < minIdle) {
throw new IllegalArgumentException("illegal maxActive " + maxActive);
}
if (getInitialSize() > maxActive) {
throw new IllegalArgumentException("illegal initialSize " + this.initialSize + ", maxActive " + maxActive);
}
if (timeBetweenLogStatsMillis > 0 && useGlobalDataSourceStat) {
throw new IllegalArgumentException("timeBetweenLogStatsMillis not support useGlobalDataSourceStat=true");
}
if (maxEvictableIdleTimeMillis < minEvictableIdleTimeMillis) {
throw new SQLException("maxEvictableIdleTimeMillis must be grater than minEvictableIdleTimeMillis");
}
if (keepAlive && keepAliveBetweenTimeMillis <= timeBetweenEvictionRunsMillis) {
throw new SQLException("keepAliveBetweenTimeMillis must be grater than timeBetweenEvictionRunsMillis");
}
if (this.driverClass != null) {
this.driverClass = driverClass.trim();
}
// spi加载
initFromSPIServiceLoader();
// 解析driver
resolveDriver();
// 设置哪一种数据类型 isMySql = true
initCheck();
// 根据driver的class 设置异常排序类
initExceptionSorter();
// 初始化有效链接的检查,类似于心跳检查各个数据库不同 意思相同pingMethod或者pingTimeout等心跳检测 mockDriver不会命中
initValidConnectionChecker();
// 是否设置了sql检查,testOnBorrow || testOnReturn || testWhileIdle
validationQueryCheck();
// 是否用了全局数据源统计 默认false
if (isUseGlobalDataSourceStat()) {
dataSourceStat = JdbcDataSourceStat.getGlobal();
if (dataSourceStat == null) {
dataSourceStat = new JdbcDataSourceStat("Global", "Global", this.dbTypeName);
JdbcDataSourceStat.setGlobal(dataSourceStat);
}
if (dataSourceStat.getDbType() == null) {
dataSourceStat.setDbType(this.dbTypeName);
}
} else {
dataSourceStat = new JdbcDataSourceStat(this.name, this.jdbcUrl, this.dbTypeName, this.connectProperties);
}
dataSourceStat.setResetStatEnable(this.resetStatEnable);
connections = new DruidConnectionHolder[maxActive];
evictConnections = new DruidConnectionHolder[maxActive];
keepAliveConnections = new DruidConnectionHolder[maxActive];
SQLException connectError = null;
// 如果配置了创建scheduler 而且是异步加载的方式 则提交task
if (createScheduler != null && asyncInit) {
for (int i = 0; i < initialSize; ++i) {
submitCreateTask(true);
}
} else if (!asyncInit) {
// 初始化连接池 如果initialSize > 0 poolingCount默认是0
while (poolingCount < initialSize) {
try {
// 创建物理链接 封装了 datasource的connection信息
PhysicalConnectionInfo pyConnectInfo = createPhysicalConnection();
// 为每个connection设置对应的holder connectionId是key 记录了每个链接上一次链接的信息
DruidConnectionHolder holder = new DruidConnectionHolder(this, pyConnectInfo);
// 赋值到连接池管理
connections[poolingCount++] = holder;
} catch (SQLException ex) {
LOG.error("init datasource error, url: " + this.getUrl(), ex);
if (initExceptionThrow) {
connectError = ex;
break;
} else {
Thread.sleep(3000);
}
}
}
// 连接池熟练大于0 赋值poolingPeak
if (poolingCount > 0) {
poolingPeak = poolingCount;
poolingPeakTime = System.currentTimeMillis();
}
}
// 创建统计连接池状态的线程,间隔是 timeBetweenLogStatsMillis
createAndLogThread();
// 初始化从连接池里获取链接的线程 = 从连接池拿物理链接并且put到map的holder中 保证不会被gc
createAndStartCreatorThread();
// 初始化从连接池里销毁的线程 间隔为 timeBetweenEvictionRunsMillis
createAndStartDestroyThread();
initedLatch.await();
init = true;
initedTime = new Date();
registerMbean();
if (connectError != null && poolingCount == 0) {
throw connectError;
}
if (keepAlive) {
// async fill to minIdle
if (createScheduler != null) {
for (int i = 0; i < minIdle; ++i) {
submitCreateTask(true);
}
} else {
this.emptySignal();
}
}
} catch (SQLException e) {
LOG.error("{dataSource-" + this.getID() + "} init error", e);
throw e;
} catch (InterruptedException e) {
throw new SQLException(e.getMessage(), e);
} catch (RuntimeException e) {
LOG.error("{dataSource-" + this.getID() + "} init error", e);
throw e;
} catch (Error e) {
LOG.error("{dataSource-" + this.getID() + "} init error", e);
throw e;
} finally {
inited = true;
lock.unlock();
if (init && LOG.isInfoEnabled()) {
String msg = "{dataSource-" + this.getID();
if (this.name != null && !this.name.isEmpty()) {
msg += ",";
msg += this.name;
}
msg += "} inited";
LOG.info(msg);
}
}
}