蟑螂数据库 “连接已关闭”

huangapple go评论69阅读模式
英文:

cockroarch DB "conn closed"

问题

var db *pgx.Conn //数据库

func ConnectCockroachDB() {
var dbUri string = "testurl"
conn, err := pgx.Connect(context.Background(), dbUri)
if err != nil {
fmt.Fprintf(os.Stderr, "无法连接到数据库:%v\n", err)
os.Exit(1)
}
db = conn
}

//返回一个DB对象的句柄
func GetDB() *pgx.Conn {
if db == nil {
ConnectCockroachDB()
}
return db
}

但是在重新启动数据库后,应用程序无法自动连接。错误是“连接已关闭”。我需要重新启动应用程序才能使应用程序正常工作。

英文:
			var db *pgx.Conn //database

			func ConnectCockroachDB() {
				var dbUri string = "testurl"
				conn, err := pgx.Connect(context.Background(), dbUri)
				if err != nil {
					fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
					os.Exit(1)
				}
				db = conn
			}

			//returns a handle to the DB object
			func GetDB() *pgx.Conn {
				if db == nil {
					ConnectCockroachDB()
				}
				return db
			}

but after i restart the DB, the application can not connect automatically. the error is "conn closed". i need to restart the application to make the app working

答案1

得分: 1

为了回答你的问题:

func GetDB() *pgx.Conn {
    if db == nil || db.IsClosed() {
        ConnectCockroachDB()
    }
    return db
}

然而,这段代码在多个 goroutine 中使用时是不安全的。应该为访问和更新全局 db 实例添加锁,以避免竞态条件。

英文:

to just answer your question:

func GetDB() *pgx.Conn {
    if db == nil || db.IsClosed() {
        ConnectCockroachDB()
    }
    return db
}

However, this code is not safe for use from multiple goroutines. There should be a lock for accessing and updating the global db instance to avoid race conditions.

答案2

得分: 1

由于您正在使用pgx,您可能希望尝试使用pgxpool进行连接:https://pkg.go.dev/github.com/jackc/pgx/v4/pgxpool

它会自动处理如果旧连接关闭了就创建一个新连接。它还已经支持并发使用。

英文:

Since you're using pgx, you might want to try using pgxpool to connect: https://pkg.go.dev/github.com/jackc/pgx/v4/pgxpool

It will automatically take care of creating a new connection if the old one got closed. It also already supports concurrent usage.

huangapple
  • 本文由 发表于 2021年9月13日 18:31:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/69161182.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定