1 回答

TA貢獻1835條經驗 獲得超7個贊
在這個任務中,我通過 mongo-go-driver 代碼庫學到了一些東西,我認為在結束這個問題之前我應該與世界分享這些東西。如果我錯了 - 請糾正我。
Connect()
如果您想利用連接池,則不應一遍又一遍地調用??雌饋砻看握{用 Connect() 時都會創建一個新套接字。defer Close()
這意味著隨著時間的推移,除非您每次都手動進行操作,否則存在套接字耗盡的風險。
All()
在 mongo-go-driver 中,當您調用執行查詢時(例如),會話會在幕后自動處理。您可以*顯式地創建和拆除會話,但您不能使用我上面提出的單例方法來使用它,而不必更改所有調用方函數。這是因為您無法再在會話上調用查詢操作,而是必須在數據庫操作本身上使用 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)}
}
這使我能夠利用連接池并保持與我們的代碼庫的向后兼容性。希望這對其他人有幫助。
- 1 回答
- 0 關注
- 153 瀏覽
添加回答
舉報