带有Postgres的Gorm客户问题过多

C0ol_Cod3r:

我在这样的管理包设置中有数据库连接,

模板文件:

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()

所以我有点困惑?我为解决连接问题所做的一切好吗?或者,还有更好的方法?

非常感谢。

戴夫:

您只需要创建一个连接,并返回相同的实例:

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
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章