5 分鐘搞懂 Golang 數據庫連接管理

本文介紹瞭如何在 Golang 中優化數據庫連接,通過有效管理連接來提高應用程序吞吐量。原文: Optimizing Database Connections in Go: Improving Throughput by Managing Open Connections Efficiently[1]

Go 的 database/sql 軟件包提供了自動化數據庫連接池,能夠幫助開發人員有效管理連接。通常情況下,開發人員會請求某個打開的連接,執行查詢,然後關閉連接以確保連接返回到池中。

開發人員常犯的一個錯誤是長時間持有數據庫連接,從而導致性能瓶頸。新請求不得不等待可用連接,造成連接池的效率受到影響。

本文將探討如何避免這一問題,並通過確定常見問題域和學習解決方法,優化 Go 應用以提高吞吐量。

基本示例

我們以一個返回僱員記錄的基本 HTTP 處理程序爲例:

func GetEmployeesHandler(w http.ResponseWriter, r *http.Request) {
    rows, err := db.Query(`SELECT id, name, email FROM employee`)
    if err != nil {
        http.Error(w, fmt.Sprintf("error querying database: %v", err), http.StatusInternalServerError)
        return
    }
    defer rows.Close()

    var employees []Employee
    for rows.Next() {
        var e Employee
        if err := rows.Scan(&e.ID, &e.Name, &e.Email); err != nil {
            http.Error(w, fmt.Sprintf("Error scanning row: %v", err), http.StatusInternalServerError)
            return
        }
        decorateEmployee(&e)
        employees = append(employees, e)
    }

    if err = rows.Err(); err != nil {
        http.Error(w, fmt.Sprintf("error during row iteration: %v", err), http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    if err := json.NewEncoder(w).Encode(employees); err != nil {
        http.Error(w, "Error encoding response", http.StatusInternalServerError)
        return
    }
}

在這個處理程序中:

乍一看,似乎沒有什麼特別的地方。不過,你會期待在壓力測試的時候獲得更好的性能。

初步性能結果

使用 Vegeta[2] 等壓力測試工具,可以模擬該端點的負載情況。在每秒 10 個請求(RPS,requests per second)的初始速率下,應用在 30 秒的測試運行中表現相對較好:

$ echo "GET http://localhost:8080/employees" | vegeta attack -duration=30s -rate=10 | tee results.bin | vegeta report
Requests      [total, rate, throughput]         300, 10.03, 5.45
Duration      [total, attack, wait]             52.095s, 29.9s, 22.196s
Latencies     [min, mean, 50, 90, 95, 99, max]  2.318s, 11.971s, 8.512s, 26.222s, 30.001s, 30.001s, 30.001s
Bytes In      [total, mean]                     2290991, 7636.64
Bytes Out     [total, mean]                     0, 0.00
Success       [ratio]                           94.67%
Status Codes  [code:count]                      0:16  200:284

然而,當我們將負載增加到 50 RPS 時,就會發現吞吐量大幅下降,請求失敗率急劇上升:

$ echo "GET http://localhost:8080/employees" | vegeta attack -duration=30s -rate=50 | tee results.bin | vegeta report
Requests      [total, rate, throughput]         1500, 50.03, 4.20
Duration      [total, attack, wait]             59.981s, 29.981s, 30s
Latencies     [min, mean, 50, 90, 95, 99, max]  2.208s, 27.175s, 30.001s, 30.001s, 30.001s, 30.002s, 30.002s
Bytes In      [total, mean]                     2032879, 1355.25
Bytes Out     [total, mean]                     0, 0.00
Success       [ratio]                           16.80%
Status Codes  [code:count]                      0:1248  200:252

(上述狀態代碼爲 0 表示測試運行過程中出現客戶端超時)

定位瓶頸

當 RPS 爲 50 時,成功率急劇下降,吞吐量降至每秒僅 4.2 個請求。爲什麼會這樣?其中一個可能的原因是,考慮到當前資源,50 RPS 是一個不合理的目標。爲了確認代碼是否可以通過修改獲得更好的性能,我們可以研究收集一些指標。其中一個指標來源是裝飾過程,但在本文中,我們將重點關注數據庫連接池統計數據。

Go 的 database/sql 軟件包可通過 DBStats 函數查看應用的數據庫池性能,會返回我們感興趣的統計信息:

可以通過添加另一個端點處理程序來輸出這些值:

func GetInfoHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    if err := json.NewEncoder(w).Encode(db.Stats()); err != nil {
        http.Error(w, "Error encoding response", http.StatusInternalServerError)
        return
    }
}

重新運行上述壓力測試,並對 /info 端點進行監控:

$ while true; do curl -s http://localhost:8080/info; sleep 2; done
...
{"MaxOpenConnections":15,"OpenConnections":15,"InUse":15,"Idle":0,"WaitCount":1434,"WaitDuration":1389188829869,"MaxIdleClosed":0,"MaxIdleTimeClosed":0,"MaxLifetimeClosed":0}
{"MaxOpenConnections":15,"OpenConnections":15,"InUse":15,"Idle":0,"WaitCount":1485,"WaitDuration":1582086078604,"MaxIdleClosed":0,"MaxIdleTimeClosed":0,"MaxLifetimeClosed":0}
{"MaxOpenConnections":15,"OpenConnections":15,"InUse":15,"Idle":0,"WaitCount":1485,"WaitDuration":1772844971842,"MaxIdleClosed":0,"MaxIdleTimeClosed":0,"MaxLifetimeClosed":0}
...

上述結果表明連接池已達到最大值(InUse: 15, Idle: 0),每個新請求都被迫等待(WaitCount 不斷增加)。換句話說,連接池基本上處於停滯狀態,從而導致了之前觀察到的延遲和超時問題!

優化連接使用

查看原始代碼,我們發現問題要麼出在查詢本身性能不佳,要麼出在遍歷結果集時每次調用裝飾函數都需要很長時間才能返回。可以嘗試在 rows.Next() 循環之外裝飾記錄,並將其移至數據庫連接使用之下,從而找出問題所在。

以下是更新後的代碼:

func GetEmployeesHandler(w http.ResponseWriter, r *http.Request) {
    rows, err := db.Query(`SELECT id, name, email FROM employee`)
    if err != nil {
        http.Error(w, fmt.Sprintf("error querying database: %v", err), http.StatusInternalServerError)
        return
    }

    var employees []Employee
    for rows.Next() {
        var e Employee
        if err := rows.Scan(&e.ID, &e.Name, &e.Email); err != nil {
            http.Error(w, fmt.Sprintf("Error scanning row: %v", err), http.StatusInternalServerError)
            return
        }
        employees = append(employees, e)
    }

    if err = rows.Err(); err != nil {
        http.Error(w, fmt.Sprintf("error during row iteration: %v", err), http.StatusInternalServerError)
        return
    }
    rows.Close()

    for i := range employees {
        decorateEmployee(&employees[i])
    }

    w.Header().Set("Content-Type", "application/json")
    if err := json.NewEncoder(w).Encode(employees); err != nil {
        http.Error(w, "Error encoding response", http.StatusInternalServerError)
        return
    }
}

在這個重構的處理程序中,我們:

優化後的性能

優化後以 50 RPS 運行相同的 Vegeta 測試,結果如下:

$ echo "GET http://localhost:8080/employees" | vegeta attack -duration=30s -rate=50 | tee results.bin | vegeta report
Requests      [total, rate, throughput]         1500, 50.03, 45.78
Duration      [total, attack, wait]             32.768s, 29.98s, 2.788s
Latencies     [min, mean, 50, 90, 95, 99, max]  2.045s, 2.502s, 2.499s, 2.692s, 2.741s, 2.856s, 2.995s
Bytes In      [total, mean]                     11817000, 7878.00
Bytes Out     [total, mean]                     0, 0.00
Success       [ratio]                           100.00%
Status Codes  [code:count]                      200:1500
...
{"MaxOpenConnections":15,"OpenConnections":1,"InUse":0,"Idle":1,"WaitCount":0,"WaitDuration":0,"MaxIdleClosed":0,"MaxIdleTimeClosed":0,"MaxLifetimeClosed":0}
{"MaxOpenConnections":15,"OpenConnections":1,"InUse":0,"Idle":1,"WaitCount":0,"WaitDuration":0,"MaxIdleClosed":0,"MaxIdleTimeClosed":0,"MaxLifetimeClosed":0}
{"MaxOpenConnections":15,"OpenConnections":1,"InUse":0,"Idle":1,"WaitCount":0,"WaitDuration":0,"MaxIdleClosed":0,"MaxIdleTimeClosed":0,"MaxLifetimeClosed":0}
...

可以看到,不僅吞吐量和延遲得到了 100% 的大幅改善,而且 OpenConnections 的總數也沒有超過 1,甚至還有閒置連接處於待機狀態,從而使 WaitCount 始終爲零!

總結

通過優化連接的處理方式,先將所有行獲取到內存中,然後立即關閉連接,而不是在執行其他 I/O 綁定操作(如裝飾記錄)時保持連接打開。這樣,數據庫連接就能儘快返回到池中,爲其他傳入請求釋放資源,從而提高吞吐量和併發性。


你好,我是俞凡,在 Motorola 做過研發,現在在 Mavenir 做技術工作,對通信、網絡、後端架構、雲原生、DevOps、CICD、區塊鏈、AI 等技術始終保持着濃厚的興趣,平時喜歡閱讀、思考,相信持續學習、終身成長,歡迎一起交流學習。爲了方便大家以後能第一時間看到文章,請朋友們關注公衆號 "DeepNoMind",並設個星標吧,如果能一鍵三連 (轉發、點贊、在看),則能給我帶來更多的支持和動力,激勵我持續寫下去,和大家共同成長進步!

參考資料

[1]

Optimizing Database Connections in Go: Improving Throughput by Managing Open Connections Efficiently: https://medium.com/@ullauri.byron/optimizing-database-connections-in-go-improving-throughput-by-managing-open-connections-7d90b2eb9169

[2]

Vegeta: https://github.com/tsenart/vegeta

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/LTyCmI4eYMqSbbSWddQAnw