我通过 mongo-go-driver 代码库在这个任务中学到了一些东西,我认为在结束这个问题之前我应该与世界分享。如果我在这里错了 - 请纠正我。
Connect()
如果您想利用连接池,则不应一遍又一遍地调用。看起来每次调用 Connect() 时,都会创建一个新套接字。这意味着除非您defer Close()
每次都手动 - 否则随着时间的推移存在套接字耗尽的风险。
在 mongo-go-driver 中,当您调用执行查询(例如All()
)时,会话会自动在后台自动处理。您可以*显式创建和拆除会话,但您不能使用我上面提出的单例方法来使用它,而无需更改所有调用者函数。这是因为您不能再对会话调用查询操作,而必须在 DB 操作本身使用 WithSession 函数来使用它
我意识到writeconcern
,readpref
并且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)}
}
这使我能够利用连接池并保持与我们的代码库的向后兼容性。希望这对其他人有帮助。