一尘不染

如何在http goroutines之间共享mysql连接?

go

我是Go菜鸟,无法找到在Go中打开mysql连接然后在http处理程序之间共享它的完整示例。到目前为止,这是我的代码,如何使用在HomeHandler中的main()中打开的db连接?

package main

import (
  "database/sql"
  "fmt"
  _ "github.com/go-sql-driver/mysql"
  "github.com/gorilla/mux"
  "log"
  "net/http"
)

func main() {

  fmt.Println("starting up")

  db, err := sql.Open("mysql", "root:@/mydb?charset=utf8")
  if err != nil {
    log.Fatalf("Error opening database: %v", err)
  }

  db.SetMaxIdleConns(100)

  r := mux.NewRouter()
  r.HandleFunc("/", HomeHandler)

  http.Handle("/", r)
  http.ListenAndServe(":8080", nil)

}

func HomeHandler(w http.ResponseWriter, r *http.Request) {

  fmt.Fprintf(w, "home")

}

阅读 175

收藏
2020-07-02

共1个答案

一尘不染

数据库/ sql程序包会自动为您管理连接池。

sql.Open(..)返回 代表连接池 而不是单个连接的句柄。如果池中的所有连接都忙,则数据库/ sql软件包会自动打开一个新连接。

将其应用于代码意味着,您只需要共享db-handle并在HTTP处理程序中使用它:

package main

import (
    "database/sql"
    "fmt"
    "github.com/gorilla/mux"
    _ "github.com/go-sql-driver/mysql"
    "log"
    "net/http"
)

var db *sql.DB // global variable to share it between main and the HTTP handler

func main() {
    fmt.Println("starting up")

    var err error
    db, err = sql.Open("mysql", "root@unix(/tmp/mysql.sock)/mydb") // this does not really open a new connection
    if err != nil {
        log.Fatalf("Error on initializing database connection: %s", err.Error())
    }

    db.SetMaxIdleConns(100)

    err = db.Ping() // This DOES open a connection if necessary. This makes sure the database is accessible
    if err != nil {
        log.Fatalf("Error on opening database connection: %s", err.Error())
    }

    r := mux.NewRouter()
    r.HandleFunc("/", HomeHandler)

    http.Handle("/", r)
    http.ListenAndServe(":8080", nil)
}

func HomeHandler(w http.ResponseWriter, r *http.Request) {
    var msg string
    err := db.QueryRow("SELECT msg FROM hello WHERE page=?", "home").Scan(&msg)
    if err != nil {
        fmt.Fprintf(w, "Database Error!")
    } else {
        fmt.Fprintf(w, msg)
    }
}
2020-07-02