我正在编写一个ruby脚本,用作Postfix SMTP访问策略委派。该脚本需要访问Tokyo Tyrant数据库。我正在使用EventMachine来处理网络连接。 EventMachine需要一个EventMachine :: Connection类,每当创建一个新连接时,它都会被EventMachine的处理循环实例化。所以对于每个连接,一个类被实例化并被销毁。
我正在从EventMachine :: Connection的post_init创建与Tokyo Tyrant的连接(即在设置连接后立即)并在连接终止后将其拆除。
我的问题是,这是否是连接到db的正确方法?即我每次都需要它连接并在完成后将其撕下来?连接到DB一次(当程序启动时)在程序关闭期间将其拆除是不是更好?如果是这样我该怎么编码呢?
我的代码是:
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 "*" }
}
问候,
拉吉
答案 0 :(得分:1)
令人惊讶的是,这个问题没有答案。
您可能需要的是一个连接池,您可以根据需要获取,使用和返回连接。
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