英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论