2017-11-29 04:08
浏览 568

Gin + Golang +数据库连接池

I would like to understand how does GIN ensures that each HTTP request gets a unique DB ( say MySQL ) connection. Here is one example code. If you see, since 'db' is a global object and therefore, the API router.GET("/person/:age"... gets access to DB. Now with load, I suppose GIN will have concurrency implemented internally. If yes, then how does it ensures that each request gets a different connection. If no, then it is single threaded imnplementation. Could anyone please correct my understanding.

package main

import (
    //  "bytes"
    _ ""

func checkErr(err error) {
    if err != nil {
    } else {

func main() {
    db, err := sql.Open("mysql", "abfl:abfl@tcp(")
    defer db.Close()
    // make sure connection is available
    err = db.Ping()
    type User struct {
        age  int
        name string
    router := gin.Default()
    // Add API handlers here
    // GET a user detail
    router.GET("/person/:age", func(c *gin.Context) {
        var (
            user   User
            result gin.H
        age := c.Param("age")
        fmt.Println("input age : '%d'", age)
        row := db.QueryRow("select age, name from user where age = ?", age)
        err = row.Scan(&user.age, &
        fmt.Printf("user : %+v
", user)
        if err != nil {
            // If no results send null
            result = gin.H{
                "user":  nil,
                "count": 0,
        } else {
            result = gin.H{
                "age":   user.age,
                "count": 1,
        c.JSON(http.StatusOK, result)
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doukenqiong0588 2017-12-04 05:38

    I got all my answer documented here :

    database/sql package handles connection pool with prepared statment very intelligently and thus removes the headache of maintaing the map of connection handle with prepared statement handle in a concurrent environment.

    解决 无用
    打赏 举报
  • dongshou2024 2017-11-29 15:58

    Establishing a new SQL connection for each HTTP request is too heavy and has no sense.
    In go there is no user-managable connection pool yet, it is handled internally by go implementation.
    sql.DB is ready to be used concurrently, so there is no worry about it.
    And GIN has nothing to do with SQL connections at all. It is fully your responsibility to handle queries/transactions properly.

    解决 无用
    打赏 举报

相关推荐 更多相似问题