donkey111111 2015-04-10 10:05
浏览 150

mysql连接应在golang中生存多长时间

I am using mysql with golang and reading this doc. It says

Although it’s idiomatic to Close() the database when you’re finished with it, the sql.DB object is designed to be long-lived. Don’t Open() and Close() databases frequently.

I don't know how long should the connnection be. For now, I open the connection each http request if necessary. Is it too frequently?

  • 写回答

2条回答 默认 最新

  • dourui9570 2015-04-10 10:41
    关注

    There is no authoritative answer, as it depends on the driver you're using. If you're using either:

    ... then you shouldn't close your sql.DB at all. The sql.DB in those cases represents a connection pool, and using it in your handlers/requests/functions means you are just using a connection from that pool (if available).

    e.g.

    var db *sql.DB
    
    func setup() error {
        var err error
        db, err = sql.Open(...)
        if err != nil {
            log.Fatal(err)
        }
    
        // Other setup-related activities
    }
    
    func main()
        err := setup()
        if err != nil {
            log.Fatal(err)
        }
    
        // No need to call `defer db.Close()` here
        http.ListenAndServe(...)
    }
    
    func SomeHandler(w http.ResponseWriter, r *http.Request) {
        u := User{}
        res, err := db.GetThings(&u)
        // No need to close this here - it's just a connection dynamically pulled
        // from our sql.DB connection pool in most cases
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)