douzi2785 2017-11-11 17:53
浏览 43
已采纳

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?