Sharing DB connections between objects using class methods in ruby?

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

+3
source share
1 answer

It is surprising that there are no answers to this question.

Perhaps you need a connection pool where you can receive, 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
+1
source

Source: https://habr.com/ru/post/1714759/


All Articles