Google Cloud SQL + Go Gin 连接超时 200 并发

Google Cloud SQL + Go Gin connection timeout with 200 concurrent

我正在尝试对产品进行负载测试。我看到很多错误来自 Google Cloud SQL“连接超时”。首先,我试图将 Google SQL 实例增加到更高,但错误仍然发生。

仅供参考,我 运行 一个应用程序通过代理连接到数据库。

任何人,请向我建议如何解决此问题。我知道这在现实世界中是不可能的。

编辑:添加示例代码

db.go

func DB() *pgxpool.Pool {

schema := os.Getenv("DB_SCHEMA")
port := os.Getenv("DB_PORT")
user := os.Getenv("DB_USERNAME")
password := os.Getenv("DB_PASSWORD")
host := os.Getenv("DB_HOST")
dbName := os.Getenv("DB_DATABASE")
sslMode := os.Getenv("DB_SSL_MODE")
sslCertificate := os.Getenv("DB_SSL_CERTIFICATE")
sslPrivateKey := os.Getenv("DB_SSL_PRIVATE_KEY")
sslRootCert := os.Getenv("DB_SSL_ROOT_CA")

connStr := fmt.Sprintf(
    "host=%s port=%s user=%s password=%s dbname=%s sslmode=%s search_path=%s sslcert=%s sslkey=%s sslrootcert=%s",
    host,
    port,
    user,
    password,
    dbName,
    sslMode,
    schema,
    sslCertificate,
    sslPrivateKey,
    sslRootCert,
)

db, err := pgxpool.Connect(context.Background(), connStr)
helpers.CheckErr(err)

return db

}

data_repository.go

func GetDataByPhone(phone string) (model.Data, error) {
db := db.DB()
defer db.Close()

var d model.Data
var strQuery = "SELECT phone, payload, updated_at " +
    "FROM example_db.public.data WHERE phone="

db.QueryRow(
    context.Background(),
    strQuery,
    phone,
).Scan(
    &d.Phone,
    &d.Payload,
    &d.UpdatedAt,
)

return d, nil

}

您似乎没有正确关闭连接。

你可以看看here你应该如何正确地打开和关闭连接。具体在 Go 中,应该是这样的:

   sqlInsert := "INSERT INTO votes(candidate, created_at, updated_at) VALUES(?, NOW(), NOW())"

    if team == "TABS" || team == "SPACES" {

    if _, err := app.db.Exec(sqlInsert, team); err != nil {
            fmt.Fprintf(w, "unable to save vote: %s", err)
            return fmt.Errorf("DB.Exec: %v", err)
    }
    fmt.Fprintf(w, "Vote successfully cast for %s!\n", team)}
    return nil

您还可以设置 connection timeout limit 为:

   // Set Maximum time (in seconds) that a connection can remain open.
   db.SetConnMaxLifetime(1800 * time.Second)`