Answer the question
In order to leave comments, you need to log in
Golang to many connections how to avoid?
There is a Method that listens on port 8083, when an event occurs, the array is passed to another method.
switch e["Event"] {
case "SomeEvent":
go someMethod(e)
}
func someMethod(e map[string]string) {
var tag User
db, err := sql.Open("mysql", "user:[email protected](10.10.10.10:3036)/dbname")
if err != nil {
log.Print(err.Error())
}
err = db.QueryRow("SELECT name FROM users where id = ?", e["ID"]).Scan(&tag.Name)
if err != nil {
panic(err.Error())
}
db.Close()
Answer the question
In order to leave comments, you need to log in
For example, you can move the db variable to a separate package and make it global there. In the init() function of this package, make a connection to the database. Then just use this variable where necessary.
I think if there are a lot of requests, you need to create a connection for each request - this is already an unnecessary expense,
connecting to the database, as mentioned above, is still better to do at the start of the service, and not with a new request,
db.SetMaxOpenConns - will solve the problem, but it seems to me again, with many requests, db.Close() will not always have time to close and again there will be problems ..
I see something like this:
func someMethod(db *sql.DB, e map[string]string) {
}
func main(){
db, err := sql.Open("mysql", "user:[email protected](10.10.10.10:3036)/dbname")
if err != nil {
log.Print(err.Error())
}
defer db.Close()
....
switch e["Event"] {
case "SomeEvent":
go someMethod(db,e)
}
...
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question