我的管理包設(shè)置中有這樣的數(shù)據(jù)庫(kù)連接,模板文件:type Template struct{}func NewAdmin() *Template { return &Template{}}數(shù)據(jù)庫(kù)文件: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}現(xiàn)在我在我的控制器包中使用該連接,就像這樣控制器模板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)}現(xiàn)在一切正常,但我現(xiàn)在已經(jīng)開(kāi)始構(gòu)建這個(gè) api 的前端。我收到pq: sorry, too many clients already大約 96 個(gè)左右的請(qǐng)求。所以我通過(guò)郵遞員運(yùn)行它并得到了相同的結(jié)果。這就是我為糾正這個(gè)問(wèn)題所做的,db := *c.T.Connection.DB()db.Find(&profile)defer db.Close()現(xiàn)在這似乎可行了,我通過(guò)郵遞員推送了 500 多個(gè)請(qǐng)求,并且運(yùn)行良好。我是客人,它db.Close()正在那里提供幫助。但是我已經(jīng)讀到連接是一個(gè)池,那么原始代碼是否應(yīng)該在不需要關(guān)閉連接的情況下工作?我認(rèn)為空閑連接是由系統(tǒng)釋放的,而不是用它們完成的?我還讀到,由于它是一個(gè)游泳池,所以不好用db.Close()。所以我有點(diǎn)困惑?我為解決連接問(wèn)題所做的工作是否有效?或者,還有更好的方法?非常感謝。
Gorm 與 Postgres 太多客戶端問(wèn)題
函數(shù)式編程
2023-06-01 18:21:06