亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Gorm 與 Postgres 太多客戶端問題

Gorm 與 Postgres 太多客戶端問題

Go
函數式編程 2023-06-01 18:21:06
我的管理包設置中有這樣的數據庫連接,模板文件:type Template struct{}func NewAdmin() *Template {   return &Template{}}數據庫文件:type Database struct {   T *Template}func (admin *Database) DB() *gorm.DB {    db, err := gorm.Open("postgres", "host=localhost port=5010 user=postgres dbname=postgres password=password sslmode=disable")    if err != nil {       panic(err)    }    return db}現在我在我的控制器包中使用該連接,就像這樣控制器模板type Template struct {  Connection *admin.Database}配置文件:type ProfilesController struct {  T *Template}func (c *ProfilesController) ProfileList(ec echo.Context) error {  profile := []models.Profile{}  c.T.Connection.DB().Find(&profile)  if len(profile) <= 0 {      reply := map[string]string{"Message": "No Profiles Found", "Code": "204"}      return ec.JSON(http.StatusBadRequest, reply)  }  return ec.JSON(http.StatusOK, profile)}現在一切正常,但我現在已經開始構建這個 api 的前端。我收到pq: sorry, too many clients already大約 96 個左右的請求。所以我通過郵遞員運行它并得到了相同的結果。這就是我為糾正這個問題所做的,db := *c.T.Connection.DB()db.Find(&profile)defer db.Close()現在這似乎可行了,我通過郵遞員推送了 500 多個請求,并且運行良好。我是客人,它db.Close()正在那里提供幫助。但是我已經讀到連接是一個池,那么原始代碼是否應該在不需要關閉連接的情況下工作?我認為空閑連接是由系統釋放的,而不是用它們完成的?我還讀到,由于它是一個游泳池,所以不好用db.Close()。所以我有點困惑?我為解決連接問題所做的工作是否有效?或者,還有更好的方法?非常感謝。
查看完整描述

1 回答

?
aluckdog

TA貢獻1847條經驗 獲得超7個贊

您只需要創建一個連接,并返回相同的實例:


type Database struct {

    T *Template

}


var db *gorm.DB


func init() {

    var err error

    db, err = gorm.Open("postgres", "host=localhost port=5010 user=postgres dbname=postgres password=password sslmode=disable")


    if err != nil {

         panic(err)

    }

}


func (admin *Database) DB() *gorm.DB {       

    return db

}


查看完整回答
反對 回復 2023-06-01
  • 1 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號