duanniu3385 2015-05-06 19:40
浏览 21
已采纳

覆盖Labix mgo中的默认writeConcern

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条回答 默认 最新

  • duankuixi1930 2015-05-07 17:03
    关注

    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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝