druid --为监控而生,具体监控如何做
结合昨天FilterChainImpl执行的FilterEventAdapter的拦截器处理逻辑,今天针对源码中的StatFilter源码进行分析,关注拦截sql执行中的监控参数处理。
connection_connect
连接时的拦截方法
public ConnectionProxy connection_connect(FilterChain chain, Properties info) throws SQLException {
//连接代理类
ConnectionProxy connection = null;
long startNano = System.nanoTime();
long startTime = System.currentTimeMillis();
long nanoSpan;
long nowTime = System.currentTimeMillis();
//数据源统计
JdbcDataSourceStat dataSourceStat = chain.getDataSource().getDataSourceStat();
//连接之前 connectingCount 数量++ 连接的最大数量 连接的最近时间
dataSourceStat.getConnectionStat().beforeConnect();
try {
//执行连接 使用ConnectionProxyImpl连接代理类获取连接
connection = chain.connection_connect(info);
nanoSpan = System.nanoTime() - startNano;
} catch (SQLException ex) {
//连接异常记录
dataSourceStat.getConnectionStat().connectError(ex);
throw ex;
}
//创建连接之后 激活的count++
dataSourceStat.getConnectionStat().afterConnected(nanoSpan);
if (connection != null) {
//获取连接的详情
JdbcConnectionStat.Entry statEntry = getConnectionInfo(connection);
//数据源连接监控增加该连接
dataSourceStat.getConnections().put(connection.getId(), statEntry);
statEntry.setConnectTime(new Date(startTime));
statEntry.setConnectTimespanNano(nanoSpan);
statEntry.setEstablishNano(System.nanoTime());
statEntry.setEstablishTime(nowTime);
statEntry.setConnectStackTrace(new Exception());
//设置激活数量
dataSourceStat.getConnectionStat().setActiveCount(dataSourceStat.getConnections().size());
}
return connection;
}
connection_close
连接关闭的拦截方法
@Override
public void connection_close(FilterChain chain, ConnectionProxy connection) throws SQLException {
if (connection.getCloseCount() == 0) {
long nowNano = System.nanoTime();
//数据源统计
JdbcDataSourceStat dataSourceStat = chain.getDataSource().getDataSourceStat();
//closeCount数量修改
dataSourceStat.getConnectionStat().incrementConnectionCloseCount();
//获取连接的详情
JdbcConnectionStat.Entry connectionInfo = getConnectionInfo(connection);
long aliveNanoSpan = nowNano - connectionInfo.getEstablishNano();
//监控池移除改连接
JdbcConnectionStat.Entry existsConnection = dataSourceStat.getConnections()