2

红宝石菜鸟在这里。对于我遇到的小问题的任何帮助将不胜感激。我正在尝试将数组放入格式化为数组的连接字符串参数中。

我的数组如下:

hosts = ["192.168.0.2:27017","192.168.0.3:27017"]

我需要将数组分开并像数组一样构造它,以便我可以一次将所有连接替换到调用中。主机的数量可能会有所不同,因此为什么它在一个阵列中。

hosts_mapped = hosts.map { |i| "'" + i.to_s + "'" }.join(",")

给我 "192.168.0.2:27017","192.168.0.3:27017" 作为我认为的字符串...或者这可能已将其映射回数组,因为我在尝试启动后遇到如下错误一个连接。

@conn = Mongo::ReplSetConnection.new([hosts_mapped], :refresh_mode => :sync, :refresh_interval => 10)

Exception `Mongo::ConnectionFailure' at gems/mongo-1.7.0/lib/mongo/util/pool_manager.rb:282 - Cannot connect to a replica set using seeds '192.168.0.2:27017
Mongo::ConnectionFailure: Cannot connect to a replica set using seeds '192.168.0.2:27017

如您所见,它似乎只引用了第一个条目。我需要将此数组保存在配置文件中,因此这就是它不直接进入上面的连接字符串的原因。对我来说,似乎我已将 hosts_mapped 映射回一个数组,但如果我将 hosts_mapped 放入,我会以正确的格式获得字符串。

"192.168.0.2:27017","192.168.0.3:27017"

工作连接字符串如下所示:

@conn = Mongo::ReplSetConnection.new(["192.168.0.2:27017","192.168.0.3:27017"], :refresh_mode => :sync, :refresh_interval => 10)

有谁知道我在这里哪里出错了?

完整的测试代码:

#!/usr/bin/ruby -d 
require "mongo" 
hosts = ["192.168.0.2:27017","192.168.0.3:27017"] 
hosts_mapped = hosts.map {|i| "'" + i.to_s + "'" }.join(",") @conn =
Mongo::ReplSetConnection.new([hosts_mapped], :refresh_mode => :sync,:refresh_interval => 10)
4

2 回答 2

0

你已经有一个数组hosts = ["192.168.0.2:27017","192.168.0.3:27017"]

如果@conn = Mongo::ReplSetConnection.new(["192.168.0.2:27017","192.168.0.3:27017"], :refresh_mode => :sync, :refresh_interval => 10)有效,您需要做的就是

@conn = Mongo::ReplSetConnection.new(hosts, :refresh_mode => :sync, :refresh_interval => 10)
于 2012-10-26T10:41:39.500 回答
0

根据文档Mongo::ReplSetConnection.new可以带一个数组:

Mongo::ReplSetConnection.new(['localhost:30000', 'localhost:30001'])

由于您已经有一个数组,您可以将其作为第一个参数传递:

hosts = ["192.168.0.2:27017","192.168.0.3:27017"]
Mongo::ReplSetConnection.new(hosts)
于 2012-10-26T10:41:24.103 回答