「已注销」 2019-01-27 19:55
浏览 521
已采纳

带有Postgres的Gorm客户问题过多

I have my database connection in my admin package setup like this,

Template File:

type Template struct{}

func NewAdmin() *Template {
   return &Template{}
}

Database File:

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
}

Now I using that connection in my controllers package, like so

Controller Teamplate

type Template struct {
  Connection *admin.Database
}

Profile File:

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

Now this was all working fine but I have now move on to building the frontend to this api. I am getting pq: sorry, too many clients already after about 96 or so requests.

So I run it though postman and got the same result. This is what I have done to correct the issue,

db := *c.T.Connection.DB()

db.Find(&profile)

defer db.Close()

Now that seems to work, I push over 500 requests though with postman and it worked fine. I am guest its the db.Close() that is helping there.

But I have read that the connection is a pool, so should the orginal code not work without needed a close on the connection? I thought that idle connections were released by the system over it was done with them? I have also read that due to it being a pool its not good to use db.Close().

So I am a little confused? Is what I done to fix the connection issue good? or is there a better way?

Many thanks.

  • 写回答

1条回答 默认 最新

  • dongquxiao8545 2019-01-27 19:57
    关注

    You need to just create the one connection, and return the same instance:

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)