# mgo-pool **Repository Path**: golang520/mgo-pool ## Basic Information - **Project Name**: mgo-pool - **Description**: mgo连接池,基于model继承实现,友好管理数据库与集合的关系,自动完成session的关闭和释放,mongodb连接池,支持mongodb多数据源 - **Primary Language**: Go - **License**: AGPL-3.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 3 - **Created**: 2024-06-05 - **Last Updated**: 2024-06-05 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### mongodb 连接池 ### 功能说明 1. 集成mongodb连接组件,有效控制连接数量 2. 基于稳定组件[=>https://gopkg.in/mgo.v2](https://gopkg.in/mgo.v2) 封装并只针对 mgo.v2封装为连接池无其它自定义处理 3. 基于model封装,需通过继承方式加载,友好的对集合、数据库进行管理 4. 通过builder构建, 支持多个mgo切换 ### 获取方式 ``` go get -u gitee.com/tym_hmm/mgo-pool ``` ### 使用案例: 1. 初始化 在main中进行进行初始化 ``` func init() { //构建builder mgoBuidler := MgoPool.NewMgoBuilder("default", "192.168.30.14:27017", "", "", "dataCenter") mgoBuidler.SetIsDebug(true) //日志保存目录,默认为/Log //mgoBuidler.SetLogDir("/Log") mgoBuidler.SetSessionSize(5) mgoBuidler.SetPoolSize(10) MgoPool.MPool.SetBuilders(mgoBuidler) //开始连接 err := MgoPool.MPool.Connection() if err != nil { fmt.Println("err", err.Error()) } } ``` --- 2.创建集合字段field ``` type FieldTest struct { Name string `bson:"name"` Id string `bson:"id"` } /** 设置集合命称 */ func (this FieldTest) CollectionName() string { return "test" } func (this *FieldTest) GetName() string { return this.Name } func (this *FieldTest) GetId() string { return this.Id } ``` --- 3.创建model ``` type testModel struct { MgoPool.BaseMgoManyModel //需继承model Field.FieldTest } func NewTestModel() *testModel { return &testModel{} } //指定builder连接 func (this *testModel) Build() { this.SetBuildName("default") } func (this *testModel) CreateRow(data *Field.FieldTest) error { this.Build() collection:=this.GetCollection() err := this.GetSession(func(session *mgo.Session, db *mgo.Database) error { //指定集合 c := db.C(collection) //写入数据 err := c.Insert(&data) if err != nil { fmt.Printf("err => %+v\n", err) return err } return nil }) if err!=nil{ fmt.Println("err", err.Err) return err.Err } return nil } //音独获取session操wt func (this *testModel) CreateRowSession(data *Field.FieldTest) error { this.Build() collection := this.GetCollection() session, db, errMgo := this.GetSessionOnly() if errMgo != nil { return errors.New(errMgo.Error()) } defer session.Close() c := db.C(collection) err := c.Insert(&data) if err != nil { return err } return nil } ``` --- 4.数据写入测试 ``` func TestMgo(t *testing.T) { var wg sync.WaitGroup number := 100000 for i := 0; i < number; i++ { wg.Add(1) go func(num int) { defer wg.Done() data := &Field.FieldTest{ Name: fmt.Sprintf("%s-%d", "test", num), Id: strconv.Itoa(num), } tModel := NewTestModel() err := tModel.CreateRow(data) if err != nil { fmt.Println("ersss", err) } else { //fmt.Println("data", data) } }(i) } wg.Wait() fmt.Println("完成") } ```