我的管理包设置中有数据库连接,如下所示,
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()
db.Close()
这对我很有帮助。
但是我已经读到连接是一个池,所以如果不需要关闭连接,原始代码就不能工作吗?我以为空闲连接是由系统释放的,而不是用它们完成的?我还读到,由于它是一个游泳池,使用起来并不好
db.Close()
.
所以我有点困惑?我为解决连接问题所做的工作是否良好?还是有更好的办法?
非常感谢。