98 lines
2.1 KiB
Go
98 lines
2.1 KiB
Go
package db
|
|
|
|
import (
|
|
"go_dreamfactory/lego/sys/log"
|
|
"go_dreamfactory/lego/sys/mgo"
|
|
"go_dreamfactory/lego/sys/redis"
|
|
)
|
|
|
|
type DBConn struct {
|
|
Redis redis.ISys
|
|
Mgo mgo.ISys
|
|
}
|
|
|
|
func newDBConn(conf DBConfig) (conn *DBConn, err error) {
|
|
conn = &DBConn{}
|
|
if conf.RedisIsCluster {
|
|
conn.Redis, err = redis.NewSys(
|
|
redis.SetRedisType(redis.Redis_Cluster),
|
|
redis.SetRedis_Cluster_Addr(conf.RedisAddr),
|
|
redis.SetRedis_Cluster_Password(conf.RedisPassword))
|
|
} else {
|
|
conn.Redis, err = redis.NewSys(
|
|
redis.SetRedisType(redis.Redis_Single),
|
|
redis.SetRedis_Single_Addr(conf.RedisAddr[0]),
|
|
redis.SetRedis_Single_Password(conf.RedisPassword),
|
|
redis.SetRedis_Single_DB(conf.RedisDB),
|
|
)
|
|
}
|
|
if err != nil {
|
|
log.Error(err.Error(), log.Field{"config", conf})
|
|
return
|
|
}
|
|
if conn.Mgo, err = mgo.NewSys(
|
|
mgo.SetMongodbUrl(conf.MongodbUrl),
|
|
mgo.SetMongodbDatabase(conf.MongodbDatabase),
|
|
); err != nil {
|
|
log.Error(err.Error(), log.Field{"config", conf})
|
|
return
|
|
}
|
|
return
|
|
}
|
|
|
|
func newSys(options *Options) (sys *DB, err error) {
|
|
sys = &DB{options: options}
|
|
err = sys.init()
|
|
return
|
|
}
|
|
|
|
type DB struct {
|
|
options *Options
|
|
local *DBConn
|
|
cross *DBConn
|
|
servers map[string]*DBConn
|
|
}
|
|
|
|
func (this *DB) init() (err error) {
|
|
if this.local, err = newDBConn(this.options.Loacl); err != nil {
|
|
return
|
|
}
|
|
if this.options.Cross.Enabled {
|
|
if this.cross, err = newDBConn(this.options.Cross); err != nil {
|
|
return
|
|
}
|
|
}
|
|
if this.options.ServerList != nil && len(this.options.ServerList) > 0 {
|
|
this.servers = make(map[string]*DBConn, len(this.options.ServerList))
|
|
for k, v := range this.options.ServerList {
|
|
if this.servers[k], err = newDBConn(v); err != nil {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
return
|
|
}
|
|
|
|
func (this *DB) Local() *DBConn {
|
|
if this.cross == nil {
|
|
log.Panic("CrossDBConn on init")
|
|
}
|
|
return this.local
|
|
}
|
|
|
|
func (this *DB) Cross() *DBConn {
|
|
if this.cross == nil {
|
|
log.Panic("CrossDBConn on init")
|
|
}
|
|
return this.cross
|
|
}
|
|
|
|
func (this *DB) ServerDBConn(stage string) (conn *DBConn) {
|
|
ok := false
|
|
conn, ok = this.servers[stage]
|
|
if !ok {
|
|
log.Panicf("DBConn:%s on init", stage)
|
|
}
|
|
return
|
|
}
|