mysql.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package clinit
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "os"
  6. "time"
  7. "github.com/astaxie/beego/orm"
  8. )
  9. type MysqlConfig struct {
  10. User string `json:"user"`
  11. Password string `json:"password"`
  12. Addr string `json:"addr"`
  13. DB string `json:"db"`
  14. Charset string `json:"charset"`
  15. MaxIdle json.Number `json:"max_idle"`
  16. MaxConn json.Number `json:"max_conn"`
  17. }
  18. func InitMySQL(conf *MysqlConfig) {
  19. dataSource := fmt.Sprintf(`%s:%s@tcp(%s)/%s?charset=%s`, conf.User, conf.Password, conf.Addr, conf.DB, conf.Charset)
  20. if err := orm.RegisterDriver("mysql", orm.DRMySQL); err != nil {
  21. fmt.Printf("register mysql driver failed. error:%s\n", err)
  22. os.Exit(1)
  23. }
  24. maxIdle, _ := conf.MaxIdle.Int64()
  25. maxConn, _ := conf.MaxConn.Int64()
  26. if err := orm.RegisterDataBase("default", "mysql", dataSource, int(maxIdle), int(maxConn)); err != nil {
  27. fmt.Printf("register mysql data base failed. error:%s", err)
  28. os.Exit(1)
  29. }
  30. db, err := orm.GetDB()
  31. if err != nil {
  32. fmt.Printf("get mysql db failed. error:%s\n", err)
  33. os.Exit(1)
  34. }
  35. db.SetConnMaxLifetime(time.Hour * 3)
  36. }