gorm: too many connections issue ?

I’m developing rest api with gin-gonic and I’m getting too many connections error. How to handle it ?

I’m on digital ocean 1GB RAM / 1CPU with mysql 5.7.9

my implementation

type Impl struct {
    DB gorm.DB
}

var i Impl

func main() {
    gin.SetMode(gin.ReleaseMode)
    r := gin.New()
    r.Use(gin.Logger())
    r.Use(gin.Recovery())

    i.InitDB()

    r.GET("/questions", func(c *gin.Context) {
        questions := i.GetRandomQuestions("userID", 10)
        c.JSON(200, gin.H{"question": questions})
    })


    r.Run(":" + os.Getenv("PORT"))
}

func (i *Impl) InitDB() {
    var err error
    i.DB, err = gorm.Open("mysql", "conn str")
    if err != nil {
        log.Fatalf("Got error when connect database, the error is '%v'", err)
    }
    i.DB.LogMode(true)
    i.DB.DB().SetMaxIdleConns(10)
    i.DB.DB().SetMaxOpenConns(100)
}

func (i *Impl) GetRandomQuestions(userID string, count int) []Question {
    var waitGroup sync.WaitGroup
    waitGroup.Add(count)
    questions := make([]Question, count)
    items := make([]Item, count)
    i.DB.Where("user_id = ? AND is_answered = ? AND RAND()<(SELECT ((?/COUNT(*))*10) FROM items)", userID, false, count).Order("RAND()").Limit(count).Find(&items)
    for index, item := range items {
        go func(item Item, index int) {
            defer waitGroup.Done()
            questions[index].Text = item
        }(item, index)
    }
    waitGroup.Wait()
    return questions
}

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 20 (2 by maintainers)

Most upvoted comments

I think this is your mysql setting problem, it can’t accept that many connections.

Gorm’s SetMaxOpenConns is using golang sql database package’s method, if it has problem, it might be driver’s issue.