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

查看:175
本文介绍了维护一个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处理程序,例如,您可以创建一个独立会话支持的本地会话只是为一个请求: / p>

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天全站免登陆