go database/sql 源碼分析(三)sql.DB資料結構

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

package sql 中最核心的的資料結構是sql.DB,    其為上層應用程式提供一個統一的抽象體,它不代表一個資料庫連接,也不代表一個串連池,其是sql的包的作者為了實現:並發訪問安全控制,串連池等諸多功能而設計的一個綜合抽象資料結構。具體見代碼注釋

221 type DB struct {#通過driverName擷取driver,通過driver的Open()方法獲得到DB的原始串連,sql.Open() 建立一個DB執行個體 222     driver driver.Driver#DB連接字串,建立DB執行個體不會理解建立串連,只有使用的時候才去建立串連 223     dsn    string 224     // numClosed is an atomic counter which represents a total number of 225     // closed connections. Stmt.openStmt checks it before cleaning closed                             226     // connections in Stmt.css.#啟動以來關閉的串連數 227     numClosed uint64 228      229     mu           sync.Mutex // protects following fields                                             #空閑串連池,使用後的串連立馬放到串連池中 230     freeConn     []*driverConn      #當db.numOpen >= db.maxOpen時,排隊等待建立的串連都會添加到改資料結構中 231     connRequests []chan connRequest#當前開啟的串連數 232     numOpen      int#當前等待建立的串連數,len(connRequests)和pendingOpens區別是:一個是等待排隊串連,還沒有獲得建立串連的資格,一個是已經拿到資格準備建立 233     pendingOpens int 234     // Used to signal the need for new connections 235     // a goroutine running connectionOpener() reads on this chan and 236     // maybeOpenNewConnections sends on the chan (one send per needed connection) 237     // It is closed during db.Close(). The close tells the connectionOpener 238     // goroutine to exit.#等待database 啟動一個獨立的goroutine建立串連所需串連,將建立的串連直接發到connRequests chan中或者放到空閑串連池 239     openerCh chan struct{}#關閉狀態 240     closed   bool#依賴關係維護,使用者維護DB和其他資料結構的依賴關係,由於資料結構之間存在相互引用和依賴以及複用,在清理關閉資源時必須把依賴關係給釋放掉 241     dep      map[finalCloser]depSet 242     lastPut  map[*driverConn]string // stacktrace of last conn's put; debug only#最大的空閑串連數 243     maxIdle  int                    // zero means defaultMaxIdleConns; negative means 0#最大串連數,0表示不受限制 244     maxOpen  int                    // <= 0 means unlimited 245 }


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.