1234567891011121314151617181920212223242526272829303132333435363738394041 |
- package clinit
- import (
- "encoding/json"
- "fmt"
- "os"
- "time"
- "github.com/astaxie/beego/orm"
- )
- type MysqlConfig struct {
- User string `json:"user"`
- Password string `json:"password"`
- Addr string `json:"addr"`
- DB string `json:"db"`
- Charset string `json:"charset"`
- MaxIdle json.Number `json:"max_idle"`
- MaxConn json.Number `json:"max_conn"`
- }
- func InitMySQL(conf *MysqlConfig) {
- dataSource := fmt.Sprintf(`%s:%s@tcp(%s)/%s?charset=%s`, conf.User, conf.Password, conf.Addr, conf.DB, conf.Charset)
- if err := orm.RegisterDriver("mysql", orm.DRMySQL); err != nil {
- fmt.Printf("register mysql driver failed. error:%s\n", err)
- os.Exit(1)
- }
- maxIdle, _ := conf.MaxIdle.Int64()
- maxConn, _ := conf.MaxConn.Int64()
- if err := orm.RegisterDataBase("default", "mysql", dataSource, int(maxIdle), int(maxConn)); err != nil {
- fmt.Printf("register mysql data base failed. error:%s", err)
- os.Exit(1)
- }
- db, err := orm.GetDB()
- if err != nil {
- fmt.Printf("get mysql db failed. error:%s\n", err)
- os.Exit(1)
- }
- db.SetConnMaxLifetime(time.Hour * 3)
- }
|