维护 mgo 会话的最佳实践 [英] Best practice to maintain a mgo session

查看:23
本文介绍了维护 mgo 会话的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在将 mongodb 和 mgo lib 用于 Web 应用程序,但我不确定我使用它的方式是否好..

I'm currently using a mongodb with mgo lib for a web application, but I'm not sure if the way I'm using it, is good one ..

package db

import (
    "gopkg.in/mgo.v2"
)

const (
    MongoServerAddr = "192.168.0.104"
    RedisServerAddr = "192.168.0.104"
)

var (
    MongoSession, err = mgo.Dial(MongoServerAddr)

    MDB  = MongoSession.DB("message")
    MCol = MDB.C("new")
    MSav = MDB.C("save")

    UDB  = MongoSession.DB("account")
    UCol = UDB.C("user")
)

我初始化 db 会话并创建接受集合和文档值的变量,所以当我需要查询一个集合时,我会使用这个变量来制作它.

I init the db session and create variables who takes the collection and document value, so when I need to query a collection, I use the variable to make it.

像这样:

func UserExist(username string) bool {
    user := Users{}
    err := db.UCol.Find(bson.M{"username": username}).One(&user)
    if err != nil {
        return false
    } else {
        return true
    }
}

那么是否有最佳实践或者这个很好..?谢谢

So is there a best practice or this one is fine ..? Thanks

推荐答案

我建议不要使用这样的全局会话.相反,您可以创建一个负责所有数据库交互的类型.例如:

I suggest not using a global session like that. Instead, you can create a type that is responsible for all the database interaction. For example:

type DataStore struct {
    session *mgo.Session
}

func (ds *DataStore) ucol() *mgo.Collection { ... }

func (ds *DataStore) UserExist(user string) bool { ... }

这种设计有很多好处.一个重要的是,它允许您同时进行多个会话,因此如果您有一个 http 处理程序,例如,您可以创建一个本地会话,该会话由一个独立会话支持,仅用于该请求:

There are many benefits to that design. An important one is that it allows you to have multiple sessions in flight at the same time, so if you have an http handler, for example, you can create a local session that is backed by an independent session just for that one request:

func (s *WebSite) dataStore() *DataStore {
    return &DataStore{s.session.Copy()}
}    

func (s *WebSite) HandleRequest(...) {
    ds := s.dataStore()
    defer ds.Close()
    ...
}

在这种情况下,mgo 驱动程序表现良好,因为会话在内部缓存和重用/维护.每个会话在使用时也将由一个独立的套接字支持,并且可以配置独立的设置,并且还将具有独立的错误处理.如果您使用单个全局会话,这些是您最终必须处理的问题.

The mgo driver behaves nicely in that case, as sessions are internally cached and reused/maintained. Each session will also be backed by an independent socket while in use, and may have independent settings configured, and will also have independent error handling. These are issues you'll eventually have to deal with if you're using a single global session.

这篇关于维护 mgo 会话的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆