doujia6503 2014-06-04 15:14
浏览 150
已采纳

使用mgo连接到副本集

I'm using mtools to spin up a replica set with 3 nodes (mlaunch --replicaset) on ports 27017, 27018, and 27019.

However I'm having difficulty actually connecting to the replica set using Dial from the mgo package. The code snippet below panics with the message no reachable servers:

type Person struct {
    Name   string `bson:"name"`
    Age    int    `bson:"age"`
}

func main() {
    session, err := mgo.Dial("localhost:27017,localhost:27018,localhost:27019")
    if err != nil {
            panic(err)
    }
    c := session.DB("mydb").C("testCollection")
    c.Insert(&Person{Name: "Foo", Age: 20})
}

How exactly does one connect to a replica set using the mgo package?

  • 写回答

1条回答 默认 最新

  • douruanfan3030 2014-06-04 16:51
    关注

    You need to run rs.initiate() to complete the initial replica set configuration. This will initiate a one member replica set. You then run rs.add() with the correct parameters for your hosts to bring the other members online.

    Here's a tutorial on the process:

    http://docs.mongodb.org/manual/tutorial/deploy-replica-set/

    Generally a good idea that any time you are having issues with running something against mongodb from within code try to connect and do the same thing via the mongo shell - it can save you much time and effort.

    To re-start this process using mlaunch you need to run it this way:

    mlaunch --init --replicaset
    

    This will initialize and launch a 3 node replica set named "replset"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64