1 回答

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
在這個(gè)任務(wù)中,我通過(guò) mongo-go-driver 代碼庫(kù)學(xué)到了一些東西,我認(rèn)為在結(jié)束這個(gè)問(wèn)題之前我應(yīng)該與世界分享這些東西。如果我錯(cuò)了 - 請(qǐng)糾正我。
Connect()
如果您想利用連接池,則不應(yīng)一遍又一遍地調(diào)用。看起來(lái)每次調(diào)用 Connect() 時(shí)都會(huì)創(chuàng)建一個(gè)新套接字。defer Close()
這意味著隨著時(shí)間的推移,除非您每次都手動(dòng)進(jìn)行操作,否則存在套接字耗盡的風(fēng)險(xiǎn)。
All()
在 mongo-go-driver 中,當(dāng)您調(diào)用執(zhí)行查詢時(shí)(例如),會(huì)話會(huì)在幕后自動(dòng)處理。您可以*顯式地創(chuàng)建和拆除會(huì)話,但您不能使用我上面提出的單例方法來(lái)使用它,而不必更改所有調(diào)用方函數(shù)。這是因?yàn)槟鸁o(wú)法再在會(huì)話上調(diào)用查詢操作,而是必須在數(shù)據(jù)庫(kù)操作本身上使用 WithSession 函數(shù)來(lái)使用它
我意識(shí)到writeconcern
,readpref
和readconcern
都可以設(shè)置為:
客戶端級(jí)別(如果不覆蓋,這些是所有內(nèi)容都將使用的默認(rèn)值)
會(huì)話級(jí)別
數(shù)據(jù)庫(kù)級(jí)
查詢級(jí)別
所以我所做的是創(chuàng)建數(shù)據(jù)庫(kù)選項(xiàng)并重載 *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)}
}
這使我能夠利用連接池并保持與我們的代碼庫(kù)的向后兼容性。希望這對(duì)其他人有幫助。
- 1 回答
- 0 關(guān)注
- 151 瀏覽
添加回答
舉報(bào)