MongoDB MongoMapper Ruby 副本集配置

MongoDB MongoMapper Ruby Replica Set Config

我在我的 Sinatra 应用程序中使用此配置通过 MongoMapper 连接到 MongoDB:

MongoMapper.connection = Mongo::Connection.new('localhost', 27017)

现在我有一个副本集,在不同的服务器上有 2 个 mongos,10.5.5.5 和 10.5.5.6。如何设置与两个 mongos 的连接?如何向此连接添加身份验证?

您应该可以设置不同的连接 per model。但我想这并不是你想要做的。

class MyModel
  include MongoMapper::Document
  connection(Mongo::Connection.new('localhost', 27017))
  set_database_name "my_database"
  # ...
end

或者有 ReplSetConnection 你可以设置你的复制集:

MongoMapper.connection = Mongo::ReplicaSetConnection.new(['10.5.5.5', 30000], [' 10.5.5.6', 30000])

而且身份验证很简单:

MongoMapper.connection = Mongo::Connection.new('localhost', 27017)
MongoMapper.database = "DBNAME"
MongoMapper.database.authenticate("USERNAME", "PASSWORD") 

我最终这样做了:

MongoMapper.connection = Mongo::MongoReplicaSetClient.new( ['10.5.5.5:27017', '10.5.5.6:27017'], :read => :primary, :rs_name => 'name', :connect_timeout => 30, :op_timeout => 30 ) MongoMapper.database = "db_name" MongoMapper.database.authenticate("user", "test123")

做工精美。