dongzhiju0324 2017-11-29 04:08
浏览 679
已采纳

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"
    "database/sql"
    "fmt"
    "github.com/gin-gonic/gin"
    _ "github.com/go-sql-driver/mysql"
    "net/http"
)

func checkErr(err error) {
    if err != nil {
        panic(err)
    } else {
        fmt.Println("successful...")
    }
}

func main() {
    db, err := sql.Open("mysql", "abfl:abfl@tcp(127.0.0.1:3306)/abfl?charset=utf8")
    checkErr(err)
    defer db.Close()
    // make sure connection is available
    err = db.Ping()
    checkErr(err)
    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, &user.name)
        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,
                "name":  user.name,
                "count": 1,
            }
        }
        c.JSON(http.StatusOK, result)
    })
    router.Run(":3000")
}
  • 写回答

2条回答 默认 最新

  • doukenqiong0588 2017-12-04 05:38
    关注

    I got all my answer documented here : https://www.vividcortex.com/resources/the-ultimate-guide-to-building-database-driven-apps-with-go

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝