在ruby中使用类方法跨对象共享DB连接?
我正在编写一个ruby脚本,用作后缀SMTP访问策略委派。脚本需要访问Tokyo Tyrant数据库。我正在使用EventMachine来处理网络连接。EventMachine需要一个EventMachine::Connection类,该类在创建新连接时由EventMachine的处理循环实例化。因此,对于每个连接,都会实例化并销毁一个类 我正在从EventMachine::connection的post_init创建一个到Tokyo Tyrant的连接(即在连接建立之后),并在连接终止后将其拆掉 我的问题是,这是否是连接到db的正确方式?(每次我需要它时就连接起来,然后在我完成后把它拆掉?)?在程序关闭期间,连接到DB一次(当程序启动时)并将其拆除不是更好吗?如果是这样,我应该如何编写代码 我的代码是:在ruby中使用类方法跨对象共享DB连接?,ruby,oop,tokyo-cabinet,eventmachine,Ruby,Oop,Tokyo Cabinet,Eventmachine,我正在编写一个ruby脚本,用作后缀SMTP访问策略委派。脚本需要访问Tokyo Tyrant数据库。我正在使用EventMachine来处理网络连接。EventMachine需要一个EventMachine::Connection类,该类在创建新连接时由EventMachine的处理循环实例化。因此,对于每个连接,都会实例化并销毁一个类 我正在从EventMachine::connection的post_init创建一个到Tokyo Tyrant的连接(即在连接建立之后),并在连接终止后将其拆
require 'rubygems'
require 'eventmachine'
require 'rufus/tokyo/tyrant'
class LineCounter < EM::Connection
ActionAllow = "action=dunno\n\n"
def post_init
puts "Received a new connection"
@tokyo = Rufus::Tokyo::Tyrant.new('server', 1978)
@data_received = ""
end
def receive_data data
@data_received << data
@data_received.lines do |line|
key = line.split('=')[0]
value = line.split('=')[1]
@reverse_client_name = value.strip() if key == 'reverse_client_name'
@client_address = value.strip() if key == 'client_address'
@tokyo[@client_address] = @reverse_client_name
end
puts @client_address, @reverse_client_name
send_data ActionAllow
end
def unbind
@tokyo.close
end
end
EventMachine::run {
host,port = "127.0.0.1", 9997
EventMachine::start_server host, port, LineCounter
puts "Now accepting connections on address #{host}, port #{port}..."
EventMachine::add_periodic_timer( 10 ) { $stderr.write "*" }
}
需要“rubygems”
需要“eventmachine”
需要“鲁弗斯/东京/暴君”
类LineCounter @收到的数据令人惊讶,这个问题没有答案
您可能需要的是一个连接池,您可以在其中获取、使用和返回所需的连接
class ConnectionPool
def initialize(&block)
@pool = [ ]
@generator = block
end
def fetch
@pool.shift or @generator and @generator.call
end
def release(handle)
@pool.push(handle)
end
def use
if (block_given?)
handle = fetch
yield(handle)
release(handle)
end
end
end
# Declare a pool with an appropriate connection generator
tokyo_pool = ConnectionPool.new do
Rufus::Tokyo::Tyrant.new('server', 1978)
end
# Fetch/Release cycle
tokyo = tokyo_pool.fetch
tokyo[@client_address] = @reverse_client_name
tokyo_pool.release(tokyo)
# Simple block-method for use
tokyo_pool.use do |tokyo|
tokyo[@client_address] = @reverse_client_name
end