druid源码分析—DruidDataSource的基本分析(二)

本文详细分析了DruidDataSource类中getConnectionInternal方法的实现,包括连接池的状态检查、连接创建与获取过程,以及异常处理机制。在获取连接时,会检查连接池是否关闭、不可用,并在资源不足时进行等待或抛出异常。同时,介绍了连接池的核心参数,如最大活跃数量、最大等待线程数等,以及如何判断和处理连接错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

druid源码分析—DruidDataSource的基本分析(二)

getConnectionInternal基本分析

DruidDataSource 参数记录

//已使用的连接数量
private int activeCount = 0;
//池内连接数量,init()方法会创建连接并赋值
private int poolingCount = 0;
//连接数量
private long connectCount = 0L;
//最高峰值记录
private int activePeak = 0;
//最高峰值记录时间
private long activePeakTime = 0;
//连接池关闭状态,调用close()方法则会置位true
private volatile boolean closed = false;
//连接池可用状态,调用close()方法则会置位true
private volatile boolean enable = true;
//禁用异常,调用close()方法则为创建异常进行赋值
private volatile DataSourceDisableException disableException = null;
//最大等待线程数量,默认为-1,可通过properties进行外部设置,当maxWaitThreadCount大于
protected volatile int maxWaitThreadCount = -1;
//核心连接存放位置
private volatile DruidConnectionHolder[] connections;
//原子类参数修改器——connectErrorCount	连接错误计数
protected static final AtomicLongFieldUpdater<DruidDataSource> connectErrorCountUpdater
            = AtomicLongFieldUpdater.newUpdater(DruidDataSource.class, "connectErrorCount");

DruidAbstractDataSource 参数记录

//默认最大活跃数量
public final static int DEFAULT_MAX_ACTIVE_SIZE = 8;
//是否致命错误
protected volatile boolean onFatalError = false;
//发生错误的最大数量,当maxActive < onFatalErrorMaxActive 则抛出异常
protected volatile int onFatalErrorMaxActive = 0;
//最大活跃数量
protected volatile int maxActive = DEFAULT_MAX_ACTIVE_SIZE;
protected ScheduledExecutorService createScheduler;

代码分析

    private DruidPooledConnection getConnectionInternal(long maxWait) throws SQLException {
   
   
    	//判断连接池是否处于关闭,处于关闭状态则抛出异常
        if (closed) {
   
   
            connectErrorCountUpdater.incrementAndGet(this);
            throw new DataSourceClosedException("dataSource already closed at " + new Date(closeTimeMillis));
        }
		//判断连接池是否不可用,不可用则抛出异常
        if (!enable) {
   
   
            connectErrorCountUpdater.incrementAndGet(this);

            if (disableException != null) {
   
   
                throw disableException;
            }

            throw new DataSourceDisableException();
        }

        final long nanos = TimeUnit.MILLISECONDS.toNanos(maxWait);
        final int maxWaitThreadCount = this.maxWaitThreadCount;
		//连接持有器
        DruidConnectionHolder holder;

        for (boolean createDirect
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值