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
CodePudding user response:
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.
CodePudding user response:
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.