【发布时间】:2019-06-20 21:12:08
【问题描述】:
我的管理包设置中有我的数据库连接,像这样,
模板文件:
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 的前端。在大约 96 个左右的请求之后,我收到了 pq: sorry, too many clients already。
所以我通过邮递员运行它并得到了相同的结果。这就是我为纠正问题所做的工作,
db := *c.T.Connection.DB()
db.Find(&profile)
defer db.Close()
现在这似乎可行,但我使用邮递员推送了 500 多个请求,并且效果很好。我是客人,它的db.Close() 正在帮助那里。
但是我已经读到连接是一个池,所以原始代码是否应该在不需要关闭连接的情况下无法工作?我认为空闲连接是由系统释放的,而不是用它们完成的?我还读到,由于它是一个池,因此使用 db.Close() 并不好。
所以我有点困惑?我为解决连接问题所做的一切好吗?还是有更好的方法?
非常感谢。
【问题讨论】:
标签: postgresql go go-gorm