Hikari目前已经是springboot的默认数据库连接池,并且以高效和轻量著称,因为代码量比较少,所以可以阅读一下,学习一下,github地址:HikariCP
实现了IConcurrentBagEntry接口,可以共享的连接,是连接池里的单个连接实体。
private static final AtomicIntegerFieldUpdater stateUpdater
Connection connection
数据库连接
long lastAccessed
上次访问毫秒数
long lastBorrowed
上次借用毫秒数
private volatile int state = 0
private volatile boolean evict
是否已经移除出连接池
private volatile ScheduledFuture> endOfLife
连接结束的最后回调
private final FastList openStatements
private final HikariPool hikariPool
hikari连接池
private final boolean isReadOnly
是否只读
private final boolean isAutoCommit
是否自动提交
static
{
stateUpdater = AtomicIntegerFieldUpdater.newUpdater(PoolEntry.class, "state");
}
静态块中就是对stateUpdater进行实例化,对state字段进行顺序更新
PoolEntry(final Connection connection, final PoolBase pool, final boolean isReadOnly, final boolean isAutoCommit)
{
this.connection = connection;
this.hikariPool = (HikariPool) pool;
this.isReadOnly = isReadOnly;
this.isAutoCommit = isAutoCommit;
this.lastAccessed = currentTime();
this.openStatements = new FastList<>(Statement.class, 16);
}
构造方法传入的参数都是一一赋值,其中的openStatements是指定sql的Statement类型的16容量的FastList。
void recycle(final long lastAccessed)
{
if (connection != null) {
this.lastAccessed = lastAccessed;
hikariPool.recycle(this);
}
}
如果连接存在,记录上次方法的时间戳,然后调用连接池的方法回收连接
void setFutureEol(final ScheduledFuture> endOfLife)
{
this.endOfLife = endOfLife;
}
设置调度任务的回调
Connection createProxyConnection(final ProxyLeakTask leakTask, final long now)
{
return ProxyFactory.getProxyConnection(this, connection, openStatements, leakTask, now, isReadOnly, isAutoCommit);
}
传入普通的连接创建一个代理连接
void resetConnectionState(final ProxyConnection proxyConnection, final int dirtyBits) throws SQLException
{
hikariPool.resetConnectionState(connection, proxyConnection, dirtyBits);
}
重置连接的状态,里面的方法涉及到位运算,为了提高运算效率。
boolean isMarkedEvicted()
{
return evict;
}
判断该连接是否已经被连接池移出
void markEvicted()
{
this.evict = true;
}
标记成已移除,将evict标成true
void evict(final String closureReason)
{
hikariPool.closeConnection(this, closureReason);
}
移除连接,调用的是连接池的closeConnection()方法,同时记录了关闭原因
long getMillisSinceBorrowed()
{
return elapsedMillis(lastBorrowed);
}
计算上次使用该连接到现在共花费了多少毫秒
Connection close()
{
ScheduledFuture> eol = endOfLife;
if (eol != null && !eol.isDone() && !eol.cancel(false)) {
LOGGER.warn("{} - maxLifeTime expiration task cancellation unexpectedly returned false for connection {}", getPoolName(), connection);
}
Connection con = connection;
connection = null;
endOfLife = null;
return con;
}
关闭连接,检查连接的最后回调是否完成,如果没有完成那么输出日志,然后将连接和回调置空后返回连接的引用。