package database import ( "fpdxfeed/config" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/mysql" "github.com/gomodule/redigo/redis" ) type Conns struct { KdDB *gorm.DB DataDb *gorm.DB Redis redis.Conn } func NewConns(conf *config.Config) (conns *Conns, err error) { // koudai数据库 user, err := conf.GetString("mysql.kd.user") if err != nil { return } password, err := conf.GetString("mysql.kd.password") if err != nil { return } host, err := conf.GetString("mysql.kd.host") if err != nil { return } port, err := conf.GetString("mysql.kd.port") if err != nil { return } database, err := conf.GetString("mysql.kd.database") if err != nil { return } kddns := user + ":" + password + "@(" + host + ":" + port + ")/" + database + "?charset=utf8&parseTime=True&loc=Asia%2FShanghai" kddb, err := gorm.Open("mysql", kddns) if err != nil { return } // datalog数据库 user, err = conf.GetString("mysql.data.user") if err != nil { return } password, err = conf.GetString("mysql.data.password") if err != nil { return } host, err = conf.GetString("mysql.data.host") if err != nil { return } port, err = conf.GetString("mysql.data.port") if err != nil { return } database, err = conf.GetString("mysql.data.database") if err != nil { return } datadns := user + ":" + password + "@(" + host + ":" + port + ")/" + database + "?charset=utf8&parseTime=True&loc=Asia%2FShanghai" datadb, err := gorm.Open("mysql", datadns) if err != nil { return } // redis数据库 host, err = conf.GetString("redis.host") if err != nil { return } port, err = conf.GetString("redis.port") if err != nil { return } auth, err := conf.GetString("redis.auth") if err != nil { return } rds, _ := connRedis(host, port, auth) conns = &Conns{ KdDB: kddb, DataDb: datadb, Redis: rds, } return } func connRedis(host string, port string, auth string) (redis.Conn, error) { rds, err := redis.Dial("tcp", host + ":" + port) if err != nil { return nil, err } if auth != "null" { if _, err = rds.Do("AUTH", auth); err != nil { rds.Close() return nil, err } } if _, err = rds.Do("SELECT", 5); err != nil { rds.Close() return nil, err } return rds, nil }