I am writing a ruby ββscript that will be used as delegation of Postfix SMTP access policy. The script must access the Tokyo Tyrant database. I use EventMachine to serve network connections. EventMachine must have an EventMachine :: Connection class that is created by an instance of the EventMachine loop with each new connection. therefore, for each connection, a class is created and destroyed.
I create a connection with Tokyo Tyrant from post_init from EventMachine :: Connection (i.e. right after the connection is established) and breaks it after the connection is completed.
My question is, is this the correct way to connect to db? those. make a connection every year I need and break it off after I finish? Wouldn't it be better to connect to the database once (when the program starts) to tear it off while the program is shutting down? If so, how should I code it?
My code is:
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 "*" }
}
taking into account,
Rajah
source
share