简体   繁体   English

谷歌云 SQL + Go Gin 连接超时 200 并发

[英]Google Cloud SQL + Go Gin connection timeout with 200 concurrent

I was trying to do load testing for the production.我正在尝试对生产进行负载测试。 I see a lot of errors get from Google Cloud SQL "connection timeout".我看到很多错误来自 Google Cloud SQL“连接超时”。 Firstly, I was trying to increases the Google SQL instance to higher, but the errors still happened.首先,我试图将 Google SQL 实例增加到更高,但错误仍然发生。

FYI, I run an application connected to the database via proxy.仅供参考,我运行一个通过代理连接到数据库的应用程序。

Anyone, please suggest to me how to fix this.任何人,请向我建议如何解决此问题。 I am OK to know it is impossible in the real world.我知道这在现实世界中是不可能的。

EDIT: Add example code编辑:添加示例代码

db.go 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 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=$1"

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

return d, nil

} }

It looks like you are not closing your connections properly.看起来您没有正确关闭连接。

You can have a look here about how you should open and close connections properly.您可以在此处查看有关如何正确打开和关闭连接的信息。 Specifically in Go, it should be something like that:具体在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

You can also set a connection timeout limit with:您还可以设置连接超时限制

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM