views:

143

answers:

1

Hello,

I am writing a ruby script to be used as Postfix SMTP access policy delegation. The script needs to access a Tokyo Tyrant database. I am using EventMachine to take care of network connections. EventMachine needs a EventMachine::Connection class that is instantiated by EventMachine‘s processing loop whenever a new connection is created. so for each connection a class is instantiated and destroyed.

I am creating a connection to Tokyo Tyrant from the post_init of the EventMachine::Connection (ie right after connection is setup) and tearing it down after connection is terminated.

My question is if this is the proper way to connect to db? ie making a connection every yime I need it and tearing it down after I am finished? Wouldn't be better to connect to DB once (when program is started) tear it down during program shutdown? If that is so how should I code that ?

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 "*" }
}

with regards,

raj

+1  A: 

Surprising there's no answers to this question.

What you probably need is a connection pool where you can fetch, use, and return connections as they are required.

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
tadman