dongtanxi5676756 2014-10-26 15:22
浏览 57
已采纳

维持mgo会话的最佳做法

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")
)

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.

Like that :

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

  • 写回答

3条回答 默认 最新

  • doujing1967 2014-10-26 18:45
    关注

    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 { ... }
    

    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()
        ...
    }
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥23 (标签-bug|关键词-密码错误加密)
  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决