R
R
rmkkmkk2017-12-01 11:58:56
go
rmkkmkk, 2017-12-01 11:58:56

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)			
}

in the method I open a connection to the database, execute a query and close the connection.
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()

When executed, to many connections crashes.
Question: How can I open a connection once and use it in a method?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Pavlyuk, 2017-12-01
@rmkkmkk

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.

R
Roman, 2017-12-12
@KirEv

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 question

Ask a Question

731 491 924 answers to any question