【问题标题】:Gorm With Postgres Too Many Client IssueGorm 的 Postgres 客户端太多问题
【发布时间】: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


    【解决方案1】:

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

    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
    }
    

    【讨论】:

    • 非常感谢它的工作原理! - 我有点困惑,我仍然返回一个指向数据库的指针,对吧?那么在 var 中设置它如何改变池的工作方式呢?
    • 您仍然返回一个指针,但现在您返回一个始终指向同一个连接的指针,然后每次调用都会返回一个指向新连接的指针
    猜你喜欢
    • 1970-01-01
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    • 2013-06-26
    相关资源
    最近更新 更多