Druid資料庫連線池原始碼分析
Druid不僅僅是一個數據庫連線池,還有很多標籤,比如統計監控、過濾器、SQL解析等。既然要分析連線池,那先看看DruidDataSource類
getConnection方法的實現:
@Override public DruidPooledConnection getConnection() throws SQLException { return getConnection(maxWait); } 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); } }
返回的是一個DruidPooledConnection,這個類後面再說;另外這裡傳入了一個long型別maxWait,應該是用來做超時處理的;init方法在getConnection方法裡面呼叫,這也是一種很好的設計;裡面的過濾器鏈的處理就不多說了。
public void init() throws SQLException { if (inited) { return; } final ReentrantLock lock = this.lock; // 使用lock而不是synchronized try { lock.lockInterruptibly(); } catch (InterruptedException e) { throw new SQLException("interrupt", e); } boolean init = false; try { if (inited) { return; } init = true; connections = new DruidConnectionHolder[maxActive]; // 陣列 try { // init connections for (int i = 0, size = getInitialSize(); i < size; ++i) { Connection conn = createPhysicalConnection(); // 生成真正的資料庫連線 DruidConnectionHolder holder = new DruidConnectionHolder(this, conn); connections[poolingCount] = holder; incrementPoolingCount(); } if (poolingCount > 0) { poolingPeak = poolingCount; poolingPeakTime = System.currentTimeMillis(); } } catch (SQLException ex) { LOG.error("init datasource error, url: " + this.getUrl(), ex); connectError = ex; } createAndLogThread(); createAndStartCreatorThread(); createAndStartDestroyThread(); 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"); } } }
我這裡做了刪減,加了一些簡單的註釋。通過這個方法,正好複習一下之前寫的那些知識點,如果感興趣,可以看看我之前寫的文章。
這裡使用了lock,並且保證只會被執行一次。根據初始容量,先生成了一批資料庫連線,用一個數組connections存放這些連線的引用,而且專門定義了一個變數poolingCount來儲存這些連線的總數量。
看到initedLatch.await有一種似曾相識的感覺
private final CountDownLatch initedLatch = new CountDownLatch(2);
這裡呼叫了await方法,那countDown方法在哪些執行緒裡面被呼叫呢
protected void createAndStartCreatorThread() { if (createScheduler == null) { String threadName = "Druid-ConnectionPool-Create-" + System.identityHashCode(this); createConnectionThread = new CreateConnectionThread(threadName); createConnectionThread.start(); return; } initedLatch.countDown(); }
這裡先判斷createScheduler這個排程執行緒池是否被設定,如果沒有設定,直接countDown;否則,就開啟一個建立資料庫連線的執行緒,當然這個執行緒的run方法還是會呼叫countDown方法。但是這裡我有一個疑問:開啟建立連線的執行緒,為什麼一定要有一個排程執行緒池呢???
難道是當資料庫連線建立失敗的時候,需要過了指定時間後,再重試?這麼理解好像有點牽強,希望高人來評論。
還有就是,當開啟destroy執行緒的時候也會呼叫countDown方法。
接著在看getConnection方法,一直呼叫到getConnectionInternal方法
DruidConnectionHolder holder; try { lock.lockInterruptibly(); } catch (InterruptedException e) { connectErrorCount.incrementAndGet(); throw new SQLException("interrupt", e); } try { if (maxWait > 0) { holder = pollLast(nanos); } else { holder = takeLast(); } } catch (InterruptedException e) { connectErrorCount.incrementAndGet(); throw new SQLException(e.getMessage(), e); } catch (SQLException e) { connectErrorCount.incrementAndGet(); throw e; } finally { lock.unlock(); } holder.incrementUseCount(); DruidPooledConnection poolalbeConnection = new DruidPooledConnection(holder); return poolalbeConnection;
我這裡還是做了刪減。大體邏輯是:先從連線池中取出DruidConnectionHolder,然後再封裝成DruidPooledConnection物件返回。再看看取holder的方法:
DruidConnectionHolder takeLast() throws InterruptedException, SQLException { try { while (poolingCount == 0) { emptySignal(); // send signal to CreateThread create connection notEmptyWaitThreadCount++; if (notEmptyWaitThreadCount > notEmptyWaitThreadPeak) { notEmptyWaitThreadPeak = notEmptyWaitThreadCount; } try { notEmpty.await(); // signal by recycle or creator } finally { notEmptyWaitThreadCount--; } notEmptyWaitCount++; if (!enable) { connectErrorCount.incrementAndGet(); throw new DataSourceDisableException(); } } } catch (InterruptedException ie) { notEmpty.signal(); // propagate to non-interrupted thread notEmptySignalCount++; throw ie; } decrementPoolingCount(); DruidConnectionHolder last = connections[poolingCount]; connections[poolingCount] = null; return last; }
這個方法非常好的詮釋了Lock-Condition的使用場景,幾行綠色的註釋解釋的很明白了,如果對empty和notEmpty看不太懂,可以去看看我之前寫的那篇文章。
這個方法的邏輯:先判斷池中的連線數,如果到0了,那麼本執行緒就得被掛起,同時釋放empty訊號,並且等待notEmpty的訊號。如果還有連線,就取出陣列的最後一個,同時更改poolingCount。
到這裡,基本理解了Druid資料庫連線池獲取連線的實現流程。但是,如果不去看看裡面的資料結構,還是會一頭霧水。我們就看看幾個基本的類,以及它們之間的持有關係。
1、DruidDataSource持有一個DruidConnectionHolder的陣列,儲存所有的資料庫連線
private volatile DruidConnectionHolder[] connections; // 注意這裡的volatile
2、DruidConnectionHolder持有資料庫連線,還有所在的DataSource等
private final DruidAbstractDataSource dataSource; private final Connection conn;
3、DruidPooledConnection持有DruidConnectionHolder,所線上程等
protected volatile DruidConnectionHolder holder; private final Thread ownerThread;
對於這種設計,我很好奇為什麼要新增一層holder做封裝,數組裡直接存放Connection好像也未嘗不可。
其實,這麼設計是有道理的。比如說,一個Connection物件可以產生多個Statement物件,當我們想同時儲存Connection和對應的多個Statement的時候,就比較糾結。
再看看DruidConnectionHolder的成員變數
private PreparedStatementPool statementPool; private final List<Statement> statementTrace = new ArrayList<Statement>(2);
這樣的話,既可以做快取,也可以做統計。
最終我們對Connection的操作都是通過DruidPooledConnection來實現,比如commit、rollback等,它們大都是通過實際的資料庫連線完成工作。而我比較關心的是close方法的實現,close方法最核心的邏輯是recycle方法:
public void recycle() throws SQLException { if (this.disable) { return; } DruidConnectionHolder holder = this.holder; if (holder == null) { if (dupCloseLogEnable) { LOG.error("dup close"); } return; } if (!this.abandoned) { DruidAbstractDataSource dataSource = holder.getDataSource(); dataSource.recycle(this); } this.holder = null; conn = null; transactionInfo = null; closed = true; }
通過最後幾行程式碼,能夠看出,並沒有呼叫實際資料庫連線的close方法,而只是斷開了之前那張圖裡面的4號引用。用這種方式,來實現資料庫連線的複用。
from: https://www.cnblogs.com/cz123/p/8117146.html