英文:
Connect to replica set using mgo
问题
我正在使用mtools
在端口27017、27018和27019上启动一个包含3个节点(mlaunch --replicaset
)的副本集。
然而,我在使用mgo包的Dial
函数连接到副本集时遇到了困难。下面的代码片段会导致恐慌,并显示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})
}
请问如何使用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
得分: 2
你需要运行rs.initiate()
来完成初始副本集配置。这将初始化一个单成员副本集。然后,你可以使用正确的参数运行rs.add()
来将其他成员带上线。
以下是该过程的教程链接:
http://docs.mongodb.org/manual/tutorial/deploy-replica-set/
通常情况下,如果你在代码中运行对mongodb的操作时遇到问题,建议尝试通过mongo shell连接并执行相同的操作,这样可以节省时间和精力。
要使用mlaunch重新启动此过程,你需要以以下方式运行它:
mlaunch --init --replicaset
这将初始化并启动一个名为"replset"的3节点副本集。
英文:
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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论