gpt4 book ai didi

mongodb - 覆盖 Labix mgo 中的默认 writeConcern

转载 作者:IT王子 更新时间:2023-10-29 01:48:14 26 4
gpt4 key购买 nike

我在我的 Go 应用程序中使用 labix mgo 作为 mongodb 驱动程序,我想知道是否有一种方法可以覆盖特定查询的默认 writeConcern

关于配置的几句话:副本集有三个节点 - 一个主节点和两个辅助节点,writeConcernreadPreference 是默认的。驱动程序使用 monotonic 一致性,这意味着所有读取都是从辅助设备完成的(当它可用时,否则 - 从主设备)。

可能会有这样的情况,当我需要在写入数据库后立即读取更新的数据 - 因为上面的 mongo 可能会返回旧数据:

// update some data
_ := collection.Update(bson.M{"_id": "some_id"}, bson.M{"key": "value"})

// the data is still not updated when I read it immediately after update
var obj interface{}
_ := collection.Find(bson.M{"_id": "some_id"}).One(&obj)

问题是:是否可以覆盖驱动程序默认的writeConcern(或驱动程序的默认consistency)并强制驱动程序等待数据写入对于某些查询,从主节点读取辅助节点还是从主节点读取?

感谢任何建议。

最佳答案

好的,经过一些研究,我最终找到了解决方案。有一种方法 SetMode 允许您更改特定数据库 session 的默认一致性模式。在我们的应用程序中,我们每次在发出请求之前都会创建主 session 的副本,然后在完成后将其关闭:

// master session is configured to use monotonic consistency
session := masterSession.Copy()

// tell mgo to read from the primary in this session
session.SetMode(mgo.Strong, true)

collection := session.DB("db").C("collection")
var obj interface{}

// now we can be sure that the following request reads the data from the primary
_ := collection.Find(bson.M{"_id": "some_id"}).One(&obj)

session.Close()

关于mongodb - 覆盖 Labix mgo 中的默认 writeConcern,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30086060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com