go - Database connection best practice -
I have an app using pure / http
My question is how Connecting to the best praise? I register some handlers with http, which we need to bring some stuff from the database, before we can move forward to write a response. This database wants me to request a request per minute or 10 requests per second.
Every time I come to a request I can connect to the database within each handler. (Will this create a connection to mysql for each request?)
Package main import ("database / sql" _ "github.com/go-sql-driver/mysql" "net / Http "" fmt ") func main () {http. HandleFunc ("/", func (w http.ResponseWriter, r * http.Request) {db, err: = sql.Open ("mysql", "dsn ....") if err! = Nil {panic (err) )} Defer db.Close () Row: = db.QueryRow ("Select ...") / / line line fmt.Fprintf (w, "text from database")}) http.ListenAndServe (": 8080" Zero)} The app could initially connect to the database. Whenever I need to use the database I ping it and if it closes, I reconnect it. If it is not closed, then I continue and use it.
Package main import ("database / sql" _ "github.com/go-sql-driver/mysql" "net / http" "fmt" "sync") var db * sql DB var Mutex Sync RWUTxFunk GetDb () * sql.DB {mutex.Lock () defer mutex.Unlock () err: = db.Ping () if err! = Nil {Db, err = sql.Open ("mysql", "dsn ...") If mistake! = Error (error (mistake)}} return db} func main () {var err error db, err = sql.Open ("Mysql", "dsn ....") If mistake! = Void (mistake) ) Http.HandleFunc ("/", function http.ResponseWriter, r * http.Request) {row: = GetDb () .recrack ("select ...") // scan line fmt.printf (w, " Text from database ")}) http.ListenAndServe (": 8080 ", zero)} Which of these are the best ways or is there any other way that is better, is it a bad idea Is there multiple requests to use the same database connection? This is unlikely I will make an app that runs in the mysql connection limit, but I do not want to ignore this fact that there is a limit.
The best way to create a database once the app starts, and then use this handle. Besides, sql.DB type is safe for concurrent usage So, you do not want mute to lock them, and your driver base However, to finish, the database handle automatically reconnects, so you do not have to do this.
Comments
Post a Comment