英文:
Overriding default writeConcern in Labix mgo
问题
我正在使用labix mgo
作为我的Go应用程序中的mongodb驱动程序,并且我想知道是否有一种方法可以覆盖特定查询的默认writeConcern
。
关于配置的一些说明:副本集有三个节点-一个主节点和两个从节点,writeConcern
和readPreference
是默认的。驱动程序使用monotonic
一致性,这意味着所有读取都是从从节点进行的(当可用时,否则从主节点进行)。
可能会有这样的情况,我需要在写入数据库后立即读取更新的数据-由于上述原因,mongo可能会返回旧数据:
// 更新一些数据
_:= collection.Update(bson.M{"_id": "some_id"}, bson.M{"key": "value"})
// 在更新后立即读取数据时,数据仍然没有更新
var obj interface{}
_:= collection.Find(bson.M{"_id": "some_id"}).One(&obj)
问题是:是否可以覆盖默认的writeConcern
(或驱动程序的默认consistency
)并强制驱动程序等待数据写入到从节点,或者对某些查询从主节点读取?
感谢任何建议。
英文:
I'm using labix mgo
as a mongodb driver in my Go app and I'm wondering if there is a way to override the default writeConcern
for specific queries.
A few words about configuration: the replica set has three nodes - one primary and two secondaries, the writeConcern
and readPreference
are default. The driver uses monotonic
consistency which means that all reads are done from the secondary (when it's available, otherwise - from the primary).
There might be cases when I need to read the updated data right after writing to the database - and because of the above mongo might return the old data:
// 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)
The question is: is it possible to override the default writeConcern
(or default consistency
of the driver) and force the driver to wait until the data is written to the secondaries OR to read from the primary for some of the queries?
Appreciate any suggestions.
答案1
得分: 0
好的,以下是翻译好的内容:
好的,在进行一些研究后,我找到了一个解决方案。有一个名为SetMode
的方法,可以让你为特定的数据库会话更改默认的一致性模式。在我们的应用程序中,我们在每次发出请求之前创建主会话的副本,然后在完成后关闭它:
// 主会话配置为使用单调一致性
session := masterSession.Copy()
// 告诉mgo在此会话中从主节点读取
session.SetMode(mgo.Strong, true)
collection := session.DB("db").C("collection")
var obj interface{}
// 现在我们可以确保以下请求从主节点读取数据
_ := collection.Find(bson.M{"_id": "some_id"}).One(&obj)
session.Close()
英文:
Ok, after doing some research I ended up with a solution. There is a method SetMode
that allows you to change a default consistency mode for a specific DB session. In our app we create a copy of the master session every time before making a request and then closing it after it's done:
// 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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论