ruby noob在这里。我对我遇到的小问题的任何帮助将不胜感激。我试图将数组放入一个连接字符串参数中,该参数格式为数组。
我的数组如下:
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_mapper映射回一个数组,但是如果我放置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)
根据文档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)
您已经有一个数组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)