6

很久很久以前,当我们使用 mgo.v2 时,我们创建了一些包装函数来复制会话,设置读取首选项并将其返回以供其他库使用,例如

func NewMonotonicConnection() (conn *Connection, success bool) {
    conn := &Connection{
        session: baseSession.Copy(),
    }
    conn.session.SetMode(mongo.Monotonic, true)

    return conn, true
}

我们现在只需在 init 函数中传递默认客户端(使用 mongo.Connect 初始化并传递给连接单例),然后像这样使用:

func NewMonotonicConnection() (conn *Connection, success bool) {
    conn = defaultConnection
    return conn, true
}

我的理解是,要利用连接池,您需要使用相同的客户端(包含在 defaultConn 中),并且会话现在在.All()/cursor 拆卸内部隐式处理。如果我在这里错了,请纠正我。

如果我们仍然可以在这些连接上设置 readpref(例如,在返回之前在此连接上设置 NearestMode),那就太好了,但是社区/标准的做法是什么?

  • 我知道我可以一遍又一遍地给 mongo.Connect 打电话,但这很贵吗?
  • 我可以创建不同的客户端——每个客户端都有不同的 readpref——但我在想,如果在那个连接上发生了写操作,它就永远不会回到从从站读取。
  • 看起来我*可以显式创建会话,但我不确定我应该或者是否有任何关于在新驱动程序中显式管理这些会话的影响。
4

1 回答 1

3

我通过 mongo-go-driver 代码库在这个任务中学到了一些东西,我认为在结束这个问题之前我应该​​与世界分享。如果我在这里错了 - 请纠正我。

Connect()如果您想利用连接池,则不应一遍又一遍地调用。看起来每次调用 Connect() 时,都会创建一个新套接字。这意味着除非您defer Close()每次都手动 - 否则随着时间的推移存在套接字耗尽的风险。

在 mongo-go-driver 中,当您调用执行查询(例如All())时,会话会自动在后台自动处理。您可以*显式创建和拆除会话,但您不能使用我上面提出的单例方法来使用它,而无需更改所有调用者函数。这是因为您不能再对会话调用查询操作,而必须在 DB 操作本身使用 WithSession 函数来使用它

我意识到writeconcernreadpref并且readconcern都可以设置为:

  • 客户端级别(如果没有被覆盖,这些是所有内容都将使用的默认值)
  • 会话级别
  • 数据库级别
  • 查询级别

所以我所做的是创建数据库选项并重载 *mongo.Database 例如:

// Database is a meta-helper that allows us to wrap and overload
// the standard *mongo.Database type
type Database struct {
    *mongo.Database
}

// NewEventualConnection returns a new instantiated Connection
// to the DB using the 'Nearest' read preference.
// Per https://github.com/go-mgo/mgo/blob/v2/session.go#L61
// Eventual is the same as Nearest, but may change servers between reads.
// Nearest: The driver reads from a member whose network latency falls within
// the acceptable latency window. Reads in the nearest mode do not consider
// whether a member is a primary or secondary when routing read operations;
// primaries and secondaries are treated equivalently.
func NewEventualConnection() (conn *Connection, success bool) {
    conn = &Connection{
        client: baseConnection.client,
        dbOptions: options.Database().
            SetReadConcern(readconcern.Local()).
            SetReadPreference(readpref.Nearest()).
            SetWriteConcern(writeconcern.New(
                writeconcern.W(1))),
    }

    return conn, true
}
// GetDB returns an overloaded Database object
func (conn Connection) GetDB(dbname string) *Database {
    dbByName := &Database{conn.client.Database(dbname, conn.dbOptions)}
}

这使我能够利用连接池并保持与我们的代码库的向后兼容性。希望这对其他人有帮助。

于 2019-09-20T20:19:01.597 回答