首页 > 解决方案 > Goroutine 在每个请求(sqlx)和代码后打开一个新的数据库连接

问题描述

让我们考虑以下 goroutine:

func main(){
    ...
    go dbGoRoutine()
    ...
}

和功能:

func dbGoRoutine() {
    db, err := sqlx.Connect("postgres", GetPSQLInfo())
    if err != nil {
        panic(err)
    }
    defer db.Close()

    ticker := time.NewTicker(10 * time.Second)
    for _ = range ticker.C {
        _, err := db.Queryx("SELECT * FROM table")
        if err != nil {
            // handle
        }
    }
}

每次函数在股票代码上迭代时,它都会打开一个 cloudSQL 连接

[service... cloudsql-proxy] 2019/11/08 17:05:05 New connection for "location:exemple-db"

我不知道为什么每次都会打开一个新连接,因为 sqlx.Connect 不在 for 循环中。

标签: kubernetesgoogle-cloud-sqlgoroutinesqlxcloud-sql-proxy

解决方案


这个问题是由于 sql 包中的 Query 函数,它返回的 Row 是:

行是查询的结果。它的光标在结果集的第一行之前开始。

这些游标使用缓存存储。

尝试使用Exec()


推荐阅读