github.com/sixexorg/magnetic-ring@v0.0.0-20191119090307-31705a21e419/central/mongo/mongo.go (about) 1 package mongo 2 3 import ( 4 "github.com/sixexorg/magnetic-ring/central/mongokey" 5 "github.com/sixexorg/magnetic-ring/config" 6 "log" 7 "strings" 8 "time" 9 10 mgo "gopkg.in/mgo.v2" 11 ) 12 13 const ( 14 col_pay string = "vote" 15 col_tx string = "tx" 16 ) 17 18 var ( 19 db_blockChain string = "mgoSession" 20 mgoSession *mgo.Session 21 keys []string = []string{"Mongo"} 22 dbinit = false 23 ) 24 25 26 func InitMongo() { 27 if dbinit { 28 return 29 } 30 31 err := loadMongoSession() 32 if err != nil { 33 panic(err) 34 } 35 dbinit = true 36 log.Println("database mongodb init sucess!!!!!!!") 37 } 38 func loadMongoSession() error { 39 mongoDBInfo := &mgo.DialInfo{ 40 Addrs: strings.Split(config.GlobalConfig.MongoCfg.Addr, ","), 41 Timeout: config.GlobalConfig.MongoCfg.Timeout * time.Second, 42 PoolLimit: config.GlobalConfig.MongoCfg.PoolLimit, 43 Database: config.GlobalConfig.MongoCfg.Database, 44 } 45 session, err := mgo.DialWithInfo(mongoDBInfo) 46 if err != nil { 47 panic(err) 48 } 49 session.SetMode(mgo.Monotonic, true) 50 mgoSession = session 51 db_blockChain = mongoDBInfo.Database 52 return nil 53 } 54 55 func VoteProvider() (*mgo.Session, *mgo.Collection) { 56 session := mgoSession.Clone() 57 col := session.DB(db_blockChain).C(col_pay) 58 return session, col 59 } 60 61 62 func TxProvider() (*mgo.Session, *mgo.Collection) { 63 session := mgoSession.Clone() 64 col := session.DB(db_blockChain).C(col_tx) 65 return session, col 66 } 67 68 func KeyProvider(prifexkey mongokey.MongoKey) (*mgo.Session, *mgo.Collection) { 69 session := mgoSession.Clone() 70 col := session.DB(db_blockChain).C(prifexkey.Value()) 71 return session, col 72 }