Go 連接池分析

連接池有兩個作用:
1.創(chuàng)建數(shù)據(jù)庫連接是一個很耗時的操作
2.控制連接數(shù)

Beego orm連接池分析
1.orm結構中的alias

type orm struct {
    alias *alias
    db    dbQuerier
    isTx  bool
}

type alias struct {
    Name         string
    Driver       DriverType
    DriverName   string
    DataSource   string
    MaxIdleConns int
    MaxOpenConns int
    DB           *sql.DB
    DbBaser      dbBaser
    TZ           *time.Location
    Engine       string
}

再看sql.DB結構

type DB struct {
    // Atomic access only. At top of struct to prevent mis-alignment
    // on 32-bit platforms. Of type time.Duration.
    waitDuration int64 // Total time waited for new connections.

    connector driver.Connector
    // numClosed is an atomic counter which represents a total number of
    // closed connections. Stmt.openStmt checks it before cleaning closed
    // connections in Stmt.css.
    numClosed uint64

    mu           sync.Mutex // protects following fields
    freeConn     []*driverConn

然后看orm的RegisterDataBase方法

db, err = sql.Open(driverName, dataSource)
    if err != nil {
        err = fmt.Errorf("register db `%s`, %s", aliasName, err.Error())
        goto end
    }

    al, err = addAliasWthDB(aliasName, driverName, db)
    if err != nil {
        goto end
    }

    ...

    for i, v := range params {
        switch i {
        case 0:
            SetMaxIdleConns(al.Name, v)
        case 1:
            SetMaxOpenConns(al.Name, v)
        }
    }

然后再到SetMaxIdleConns方法里面看

func SetMaxIdleConns(aliasName string, maxIdleConns int) {
    al := getDbAlias(aliasName)
    al.MaxIdleConns = maxIdleConns
    al.DB.SetMaxIdleConns(maxIdleConns)
}

其實最終還是調用了go的database/sql 里的方法 al.DB.SetMaxIdleConns,其中al是一個sql實例
即調用了sql.DB.SetMaxIdleConns方法

大家都知道,go的sql本來就是用的連接池。
那么我們繼續(xù)看看go的sql包連接池是怎樣實現(xiàn)的。
我們先看sql.DB這個結構體

type DB struct {
    // Atomic access only. At top of struct to prevent mis-alignment
    // on 32-bit platforms. Of type time.Duration.
    waitDuration int64 // Total time waited for new connections.

    connector driver.Connector
    // numClosed is an atomic counter which represents a total number of
    // closed connections. Stmt.openStmt checks it before cleaning closed
    // connections in Stmt.css.
    numClosed uint64

    mu           sync.Mutex // protects following fields
    freeConn     []*driverConn

注意“freeConn []*driverConn”,這個就是存放連接的池子。

db.conn這個方法里面,技術和重新分配db.freeConn

numFree := len(db.freeConn)

那么db.conn這個方法在哪里調用呢?
db.prepare,db.exec,db.query等查詢的時候。
到此,我們可以一窺Go在sql連接處理上的大概了。

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容