druidDruid

Druid 获取连接流程

2022-02-13  本文已影响0人  晴天哥_王志

连接获取流程

连接获取源码

    public DruidPooledConnection getConnectionDirect(long maxWaitMillis) throws SQLException {
        int notFullTimeoutRetryCnt = 0;
        for (;;) {
            // handle notFullTimeoutRetry
            DruidPooledConnection poolableConnection;
            try {
                // 通过getConnectionInternal来获取连接
                poolableConnection = getConnectionInternal(maxWaitMillis);
            } catch (GetConnectionTimeoutException ex) {
                throw ex;
            }
          
            // 检测连接的可用性等操作
            if (testOnBorrow) {
                // 获取连接的时候检测连接可用性
            } else {
                Connection realConnection = poolableConnection.conn;

                if (testWhileIdle) {
                    // 检测是否超过空闲时间
                }
            }

            // 省略部分代码
            return poolableConnection;
        }
    }
    private DruidPooledConnection getConnectionInternal(long maxWait) throws SQLException {

        final long nanos = TimeUnit.MILLISECONDS.toNanos(maxWait);
        final int maxWaitThreadCount = this.maxWaitThreadCount;

        // 创建数据库连接的逻辑
        DruidConnectionHolder holder;
        for (boolean createDirect = false;;) {
            try {
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                throw new SQLException("interrupt", e);
            }

            try {
                connectCount++;
                // 获取连接对象
                if (maxWait > 0) {
                    holder = pollLast(nanos);
                } else {
                    holder = takeLast();
                }

                if (holder != null) {
                    activeCount++;
                    if (activeCount > activePeak) {
                        activePeak = activeCount;
                        activePeakTime = System.currentTimeMillis();
                    }
                }
            } catch (InterruptedException e) {
                throw new SQLException(e.getMessage(), e);
            } catch (SQLException e) {
                throw e;
            } finally {
                lock.unlock();
            }
            break;
        }

        holder.incrementUseCount();

        DruidPooledConnection poolalbeConnection = new DruidPooledConnection(holder);
        return poolalbeConnection;
    }
    DruidConnectionHolder takeLast() throws InterruptedException, SQLException {
        try {
            // 信号量的通知
            while (poolingCount == 0) {
                emptySignal(); // send signal to CreateThread create connection

                try {
                    notEmpty.await(); // signal by recycle or creator
                } finally {
                    notEmptyWaitThreadCount--;
                }
            }
        } catch (InterruptedException ie) {
            throw ie;
        }

        // 从connections获取最后一个连接
        decrementPoolingCount(); // 下标减一后返回最后一个连接
        DruidConnectionHolder last = connections[poolingCount];
        connections[poolingCount] = null;

        return last;
    }

    private DruidConnectionHolder pollLast(long nanos) throws InterruptedException, SQLException {
        long estimate = nanos;

        for (;;) {
            if (poolingCount == 0) {
                emptySignal(); // send signal to CreateThread create connection

                try {
                    long startEstimate = estimate;
                    estimate = notEmpty.awaitNanos(estimate); 
                    notEmptyWaitCount++;
                    notEmptyWaitNanos += (startEstimate - estimate);
                } catch (InterruptedException ie) {
                    throw ie;
                } finally {
                    notEmptyWaitThreadCount--;
                }

                if (poolingCount == 0) {
                    if (estimate > 0) {
                        continue;
                    }
                    waitNanosLocal.set(nanos - estimate);
                    return null;
                }
            }

            // 从connections获取最后一个连接
            decrementPoolingCount();// 下标减一后返回最后一个连接
            DruidConnectionHolder last = connections[poolingCount];
            connections[poolingCount] = null;

            long waitNanos = nanos - estimate;
            last.setLastNotEmptyWaitNanos(waitNanos);

            return last;
        }
    }

CreateConnectionThread创建连接

    public class CreateConnectionThread extends Thread {

        public CreateConnectionThread(String name){
            super(name);
            this.setDaemon(true);
        }

        public void run() {

            initedLatch.countDown();

            long lastDiscardCount = 0;
            int errorCount = 0;
            for (;;) {
                try {
                    lock.lockInterruptibly();
                } catch (InterruptedException e2) {
                    break;
                }

                long discardCount = DruidDataSource.this.discardCount;
                boolean discardChanged = discardCount - lastDiscardCount > 0;
                lastDiscardCount = discardCount;

                try {
                    boolean emptyWait = true;

                    // 判断是否需要等待连接池为空的信号量 empty.wait()
                    if (emptyWait) {
                        // 必须存在线程等待,才创建连接
                        if (poolingCount >= notEmptyWaitThreadCount //
                                && (!(keepAlive && activeCount + poolingCount < minIdle))
                                && !isFailContinuous()
                        ) {
                            empty.await();
                        }

                        // 防止创建超过maxActive数量的连接
                        if (activeCount + poolingCount >= maxActive) {
                            empty.await();
                            continue;
                        }
                    }

                } catch (InterruptedException e) {
                    break;
                } finally {
                    lock.unlock();
                }

                // 负责创建连接
                PhysicalConnectionInfo connection = null;
                try {
                    connection = createPhysicalConnection();
                } catch (Error e) {
                    setFailContinuous(true);
                    break;
                }

                // 添加新建的连接
                boolean result = put(connection);

                errorCount = 0; // reset errorCount
            }
        }
    }
    protected boolean put(PhysicalConnectionInfo physicalConnectionInfo) {
        DruidConnectionHolder holder = null;
        try {
            holder = new DruidConnectionHolder(DruidDataSource.this, physicalConnectionInfo);
        } catch (SQLException ex) {
            lock.lock();
            try {
                if (createScheduler != null) {
                    clearCreateTask(physicalConnectionInfo.createTaskId);
                }
            } finally {
                lock.unlock();
            }
            LOG.error("create connection holder error", ex);
            return false;
        }

        return put(holder, physicalConnectionInfo.createTaskId);
    }

    private boolean put(DruidConnectionHolder holder, long createTaskId) {
        lock.lock();
        try {
            if (poolingCount >= maxActive) {
                return false;
            }
            // 放置新增的连接
            connections[poolingCount] = holder;
            incrementPoolingCount();

            if (poolingCount > poolingPeak) {
                poolingPeak = poolingCount;
                poolingPeakTime = System.currentTimeMillis();
            }
            // 通知获取连接的线程
            notEmpty.signal();
            notEmptySignalCount++;

            if (createScheduler != null) {
                clearCreateTask(createTaskId);

                if (poolingCount + createTaskCount < notEmptyWaitThreadCount //
                    && activeCount + poolingCount + createTaskCount < maxActive) {
                    emptySignal();
                }
            }
        } finally {
            lock.unlock();
        }
        return true;
    }
上一篇下一篇

猜你喜欢

热点阅读