douzi2785
2017-11-11 17:53
浏览 42

MongoDB:我是否应该一直保持全球会议?

Here is a snippet of my DAO implementation:

type (
    User struct {
        Name string `json:"name" bson:"name"`
        ...
    }

    UserDAO struct {
        *mgo.Database
    }
)

func NewUserDAO() (*UserDAO, error) {
    session, err := mgo.Dial("mongodb://127.0.0.1:27017/test")
    if err != nil {
        return nil, err
    }

    return &UserDAO{session.DB("")}, nil
}

func (d *UserDAO) Insert(user User) error {
    return d.C("users").Insert(user)
}

func (d *CandleDAO) Find(name string) ([]User, error) {
    var result []User
    if err := d.C("users").Find(bson.M{"name": name)}).Sort("time").All(&result); err != nil {
        return nil, err
    }
    return result, nil
}

...

func (d *CandleDAO) Close() {
    d.Session.Close()
}

And here is how I invoke it:

dao, err := dao.NewUserDAO()
if err != nil {
    Log.Error(err.Error())
    return
}

// close session... is this OK?
defer dao.Close()

users, err := dao.Find(&broker.Symbol{"BTC", "USD"}); if err != nil {
    Log.Error(err.Error())
    return
}

for i, user := range users {
    fmt.Printf("%d ==> %v
", i, user)
}

The code above works... and my question is simple: shall I keep a global mgo.Database instance or is it correct to always close the session when I'm finished and create a new one whenever I need?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtbiszu7724 2017-11-13 21:07
    已采纳

    Per the main package docs:

    New sessions are typically created by calling session.Copy on the initial session obtained at dial time. These new sessions will share the same cluster information and connection pool, and may be easily handed into other methods and functions for organizing logic. Every session created must have its Close method called at the end of its life time, so its resources may be put back in the pool or collected, depending on the case.

    Meaning: at startup you should Dial and save that session, and for each call to NewUserDAO you should Clone the initial Session created with Dial.

    点赞 评论

相关推荐 更多相似问题