我的管理包設置中有這樣的數據庫連接,模板文件: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
}
- 1 回答
- 0 關注
- 182 瀏覽
添加回答
舉報
0/150
提交
取消