「已注销」 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 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐