DruidDataSource詳解(二)

DruidDataSource源碼解析

獲取連接,獲取連接時(shí)會(huì)先根據(jù)配置參數(shù)初始化連接池。如果配置有maxWaitMillis則等待maxWaitMillis時(shí)間后仍不能獲取連接則拋出GetConnectionTimeoutException異常。具體代碼如下:
public DruidPooledConnection getConnection(long maxWaitMillis) throws SQLException {
    init();//初始化連接池
    if (filters.size() > 0) {
        FilterChainImpl filterChain = new FilterChainImpl(this);
        return filterChain.dataSource_connect(this, maxWaitMillis);
    } else {
        return getConnectionDirect(maxWaitMillis);
    }
} 
public DruidPooledConnection getConnectionDirect(long maxWaitMillis) throws SQLException {
    int notFullTimeoutRetryCnt = 0;
    for (;;) {
        // handle notFullTimeoutRetry
        DruidPooledConnection poolableConnection;
        try {
           //等待一定時(shí)間后,仍舊獲取不到連接則拋出GetConnectionTimeoutException異常
            poolableConnection = getConnectionInternal(maxWaitMillis);/
        } catch (GetConnectionTimeoutException ex) {
         ....
        }
       //testOnborrow是否為true,如果是則檢驗(yàn)連接的有效性,如果為無效連接則拋棄該連接并重新獲取
        if (isTestOnBorrow()) {
            boolean validate = testConnectionInternal(poolableConnection.getConnection());
            if (!validate) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("skip not validate connection.");
                }
                Connection realConnection = poolableConnection.getConnection();
                discardConnection(realConnection);
                continue;
            }
        } else {
            Connection realConnection = poolableConnection.getConnection();
            if (realConnection.isClosed()) {
                discardConnection(null); // 傳入null,避免重復(fù)關(guān)閉
                continue;
            }
             //如果testWhileIdle是true并且空閑時(shí)間大于timeBetweenEvictionRunsMillis則驗(yàn)證連接是否有效,如果無效關(guān)閉連接
            if (isTestWhileIdle()) {
                final long currentTimeMillis = System.currentTimeMillis();
                final long lastActiveTimeMillis = poolableConnection.getConnectionHolder().getLastActiveTimeMillis();
                final long idleMillis = currentTimeMillis - lastActiveTimeMillis;
                long timeBetweenEvictionRunsMillis = this.getTimeBetweenEvictionRunsMillis();
                if (timeBetweenEvictionRunsMillis <= 0) {
                    timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
                }
                if (idleMillis >= timeBetweenEvictionRunsMillis) {
                    boolean validate = testConnectionInternal(poolableConnection.getConnection());
                    if (!validate) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("skip not validate connection.");
                        }
                        discardConnection(realConnection);
                        continue;
                    }
                }
            }
        }
        if (isRemoveAbandoned()) {
            StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
            poolableConnection.setConnectStackTrace(stackTrace);
            poolableConnection.setConnectedTimeNano();
            poolableConnection.setTraceEnable(true);

            synchronized (activeConnections) {
                activeConnections.put(poolableConnection, PRESENT);
            }
        }

        if (!this.isDefaultAutoCommit()) {
            poolableConnection.setAutoCommit(false);
        }

        return poolableConnection;
    }
}
初始化線程池
    public void init() throws SQLException {
     if (inited) {
        return;
     }
    final ReentrantLock lock = this.lock;//默認(rèn)非公平鎖,通過DruidDataSource構(gòu)造函數(shù)可以修改鎖策略   
    try {
        lock.lockInterruptibly();
    } catch (InterruptedException e) {
        throw new SQLException("interrupt", e);
    }
    boolean init = false;
    try {
        if (inited) {
            return;
        }
        init = true;

        initStackTrace = Utils.toString(Thread.currentThread().getStackTrace());
        this.id = DruidDriver.createDataSourceId();
        if (this.id > 1) {
            long delta = (this.id - 1) * 100000;
            this.connectionIdSeed.addAndGet(delta);
            this.statementIdSeed.addAndGet(delta);
            this.resultSetIdSeed.addAndGet(delta);
            this.transactionIdSeed.addAndGet(delta);
        }

        if (this.jdbcUrl != null) {
            this.jdbcUrl = this.jdbcUrl.trim();
            initFromWrapDriverUrl();
        }

        if (this.dbType == null || this.dbType.length() == 0) {
            this.dbType = JdbcUtils.getDbType(jdbcUrl, null);
        }

        for (Filter filter : filters) {
            filter.init(this);
        }

        if (JdbcConstants.MYSQL.equals(this.dbType) || //
            JdbcConstants.MARIADB.equals(this.dbType)) {
            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 (this.driverClass != null) {
            this.driverClass = driverClass.trim();
        }

        initFromSPIServiceLoader();

        if (this.driver == null) {
            if (this.driverClass == null || this.driverClass.isEmpty()) {
                this.driverClass = JdbcUtils.getDriverClassName(this.jdbcUrl);
            }

            if (MockDriver.class.getName().equals(driverClass)) {
                driver = MockDriver.instance;
            } else {
                driver = JdbcUtils.createDriver(driverClassLoader, driverClass);
            }
        } else {
            if (this.driverClass == null) {
                this.driverClass = driver.getClass().getName();
            }
        }

        initCheck();//如果為oracle數(shù)據(jù)庫或者DB2數(shù)據(jù)庫則初始化check

        initExceptionSorter();//初始化ExceptionSorter
        initValidConnectionChecker();//初始化ConnectionChecker
        validationQueryCheck();

        if (isUseGlobalDataSourceStat()) {
            dataSourceStat = JdbcDataSourceStat.getGlobal();
            if (dataSourceStat == null) {
                dataSourceStat = new JdbcDataSourceStat("Global", "Global", this.dbType);
                JdbcDataSourceStat.setGlobal(dataSourceStat);
            }
            if (dataSourceStat.getDbType() == null) {
                dataSourceStat.setDbType(this.getDbType());
            }
        } else {
            dataSourceStat = new JdbcDataSourceStat(this.name, this.jdbcUrl, this.dbType, this.connectProperties);
        }
        dataSourceStat.setResetStatEnable(this.resetStatEnable);

        connections = new DruidConnectionHolder[maxActive];

        SQLException connectError = null;

        try {
            // 按照配置參數(shù)initialSize初始化連接池
            for (int i = 0, size = getInitialSize(); i < size; ++i) {
                // createPhysicalConnection() 創(chuàng)建物理連接,后邊我們會(huì)看到這個(gè)物理連接是怎么創(chuàng)建的,會(huì)讓創(chuàng)建連接線程等待,當(dāng)
                Connection conn = createPhysicalConnection();
                DruidConnectionHolder holder = new DruidConnectionHolder(this, conn);
                connections[poolingCount] = holder;
                incrementPoolingCount();//增加連接池可用連接數(shù)量即poolingCount++
            }

            if (poolingCount > 0) {
                poolingPeak = poolingCount;
                poolingPeakTime = System.currentTimeMillis();
            }
        } catch (SQLException ex) {
            LOG.error("init datasource error, url: " + this.getUrl(), ex);
            connectError = ex;
        }
        createAndLogThread();//如果配置timeBetweenLogStatsMillis則創(chuàng)建log線程每隔指定時(shí)間記錄連接池狀態(tài)
        createAndStartCreatorThread();//創(chuàng)建并且啟動(dòng)線程在存在等待獲取連接線程的的時(shí)候,創(chuàng)建連接。
        createAndStartDestroyThread();//創(chuàng)建并啟動(dòng)銷毀線程
        initedLatch.await();
        initedTime = new Date();
        registerMbean();
        if (connectError != null && poolingCount == 0) {
            throw connectError;
        }
    } catch (SQLException e) {
        LOG.error("dataSource init error", e);
        throw e;
    } catch (InterruptedException e) {
        throw new SQLException(e.getMessage(), e);
    } finally {
        inited = true;
        lock.unlock();

        if (init && LOG.isInfoEnabled()) {
            LOG.info("{dataSource-" + this.getID() + "} inited");
        }
    }
}
創(chuàng)建物理連接,可以看到創(chuàng)建物理連接很簡單,就是根據(jù)JDBC去創(chuàng)建connection
public Connection createPhysicalConnection(String url, Properties info) throws SQLException {
    Connection conn;
    if (getProxyFilters().size() == 0) {
        conn = getDriver().connect(url, info);
    } else {
        conn = new FilterChainImpl(this).connection_connect(info);
    }

    createCount.incrementAndGet();

    return conn;
}
下面再看看createAndStartCreatorThread 是什么東西,可以看到DruidDataSource會(huì)啟動(dòng)一個(gè)線程當(dāng)活動(dòng)連接數(shù)+池中的連接數(shù)小于maxActive時(shí)并且池中連接數(shù)小于等待獲取連接的線程數(shù)時(shí)會(huì)創(chuàng)建新的物理連接并放到連接池中。
 protected void createAndStartCreatorThread() {
    if (createScheduler == null) {
        String threadName = "Druid-ConnectionPool-Create-" + System.identityHashCode(this);
        createConnectionThread = new CreateConnectionThread(threadName);
        createConnectionThread.start();
        return;
    }

    initedLatch.countDown();
}
public class CreateConnectionThread extends Thread {

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

    public void run() {
        initedLatch.countDown();

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

            try {
                // 必須存在線程等待,才創(chuàng)建連接
                if (poolingCount >= notEmptyWaitThreadCount) {
                    empty.await();
                }

                // 防止創(chuàng)建超過maxActive數(shù)量的連接
                if (activeCount + poolingCount >= maxActive) {
                    empty.await();
                    continue;
                }

            } catch (InterruptedException e) {
                lastCreateError = e;
                lastErrorTimeMillis = System.currentTimeMillis();
                break;
            } finally {
                lock.unlock();
            }

            Connection connection = null;

            try {
                connection = createPhysicalConnection();
            } catch (SQLException e) {
                LOG.error("create connection error, url: " + jdbcUrl, e);

                errorCount++;

                if (errorCount > connectionErrorRetryAttempts && timeBetweenConnectErrorMillis > 0) {
                    if (breakAfterAcquireFailure) {
                        break;
                    }

                    try {
                        Thread.sleep(timeBetweenConnectErrorMillis);
                    } catch (InterruptedException interruptEx) {
                        break;
                    }
                }
            } catch (RuntimeException e) {
                LOG.error("create connection error", e);
                continue;
            } catch (Error e) {
                LOG.error("create connection error", e);
                break;
            }

            if (connection == null) {
                continue;
            }

            put(connection);

            errorCount = 0; // reset errorCount
        }
    }
}
最后我們?cè)倏聪耤reateAndStartDestroyThread 做了什么事情, createAndStartDestroyThread該方法有兩種回收連接池的策略,第一種是通過作業(yè)調(diào)度第二種是通過Thread.sleep方法。兩種策略按timeBetweenEvictionRunsMillis間隔調(diào)度執(zhí)行destoryTask;destoryTask的 shrink(true) 主要根據(jù)配置參數(shù)判斷線程池中連接的空閑時(shí)間idleMillis 是否大于等于 minEvictableIdleTimeMillis,如果是則關(guān)閉該連接。removeAbandoned()方法主要是在配置連接泄露處理策略時(shí),關(guān)閉泄露的連接
       protected void createAndStartDestroyThread() {
    destoryTask = new DestroyTask();

    if (destroyScheduler != null) {
        long period = timeBetweenEvictionRunsMillis;
        if (period <= 0) {
            period = 1000;
        }
        destroySchedulerFuture = destroyScheduler.scheduleAtFixedRate(destoryTask, period, period,
                                                                      TimeUnit.MILLISECONDS);
        initedLatch.countDown();
        return;
    }

    String threadName = "Druid-ConnectionPool-Destroy-" + System.identityHashCode(this);
    destroyConnectionThread = new DestroyConnectionThread(threadName);
    destroyConnectionThread.start();
}
 public class DestroyTask implements Runnable {

    @Override
    public void run() {
        shrink(true);

        if (isRemoveAbandoned()) {
            removeAbandoned();
        }
    }

}
public class DestroyConnectionThread extends Thread {

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

    public void run() {
        initedLatch.countDown();

        for (;;) {
            // 從前面開始刪除
            try {
                if (closed) {
                    break;
                }

                if (timeBetweenEvictionRunsMillis > 0) {
                    Thread.sleep(timeBetweenEvictionRunsMillis);
                } else {
                    Thread.sleep(1000); //
                }

                if (Thread.interrupted()) {
                    break;
                }

                destoryTask.run();
            } catch (InterruptedException e) {
                break;
            }
        }
}
removeAbandoned處理邏輯
public int removeAbandoned() {
    int removeCount = 0;

    long currrentNanos = System.nanoTime();

    List<DruidPooledConnection> abandonedList = new ArrayList<DruidPooledConnection>();

    synchronized (activeConnections) {
        Iterator<DruidPooledConnection> iter = activeConnections.keySet().iterator();

        for (; iter.hasNext();) {
            DruidPooledConnection pooledConnection = iter.next();

            if (pooledConnection.isRunning()) {
                continue;
            }

            long timeMillis = (currrentNanos - pooledConnection.getConnectedTimeNano()) / (1000 * 1000);

            if (timeMillis >= removeAbandonedTimeoutMillis) {
                iter.remove();
                pooledConnection.setTraceEnable(false);
                abandonedList.add(pooledConnection);
            }
        }
    }

    if (abandonedList.size() > 0) {
        for (DruidPooledConnection pooledConnection : abandonedList) {
            synchronized (pooledConnection) {
                if (pooledConnection.isDisable()) {
                    continue;
                }
            }
            
            JdbcUtils.close(pooledConnection);
            pooledConnection.abandond();
            removeAbandonedCount++;
            removeCount++;

            if (isLogAbandoned()) {
                StringBuilder buf = new StringBuilder();
                buf.append("abandon connection, owner thread: ");
                buf.append(pooledConnection.getOwnerThread().getName());
                buf.append(", connected time nano: ");
                buf.append(pooledConnection.getConnectedTimeNano());
                buf.append(", open stackTrace\n");

                StackTraceElement[] trace = pooledConnection.getConnectStackTrace();
                for (int i = 0; i < trace.length; i++) {
                    buf.append("\tat ");
                    buf.append(trace[i].toString());
                    buf.append("\n");
                }

                LOG.error(buf.toString());
            }
        }
    }

    return removeCount;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,732評(píng)論 6 539
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,214評(píng)論 3 426
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 177,781評(píng)論 0 382
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,588評(píng)論 1 316
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 72,315評(píng)論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,699評(píng)論 1 327
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,698評(píng)論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,882評(píng)論 0 289
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,441評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 41,189評(píng)論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,388評(píng)論 1 372
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,933評(píng)論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,613評(píng)論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,023評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,310評(píng)論 1 293
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 52,112評(píng)論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,334評(píng)論 2 377

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,818評(píng)論 18 139
  • 從三月份找實(shí)習(xí)到現(xiàn)在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發(fā)崗...
    時(shí)芥藍(lán)閱讀 42,330評(píng)論 11 349
  • 轉(zhuǎn)自:http://blog.csdn.net/jackfrued/article/details/4492194...
    王帥199207閱讀 8,578評(píng)論 3 93
  • 青衫不華閱讀 70評(píng)論 0 0
  • 如果你目標(biāo)足夠堅(jiān)定,跑得足夠快,你根本不會(huì)理會(huì)別人的眼光。不,你甚至不會(huì)想到前面這句話——而最近可以想一想這些東西...
    竹說閱讀 1,584評(píng)論 0 1