Rubyでクラスメソッドを使用してオブジェクト間でDB接続を共有しますか?

StackOverflow https://stackoverflow.com/questions/1253620

質問

私はPostfixのSMTPアクセスポリシー委譲として使用するRubyスクリプトを書いています。このスクリプトは、東京タイラントデータベースにアクセスする必要があります。私は、ネットワーク接続の世話をするためにEventMachineを使用しています。 EventMachineは、新しい接続が作成されるたびにEventMachineの処理ループによってインスタンス化されEventMachine :: Connectionクラスを必要とします。その結果、各接続のためのクラスは、インスタンス化および破壊されます。

私はEventMachine ::コネクション(接続は、すなわち直後のセットアップ)のpost_initから東京暴君への接続を作成し、接続が終了した後、それを切断しています。

これは、DBに接続するために、適切な方法であれば、

私の質問はありますか?すなわち、接続、私はそれを必要とするすべてのyime作ると私は終わっていた後、それを引き裂きますか?一度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 "*" }
}

に関して、

ラジ

役に立ちましたか?

解決

この質問に対する答えはありません驚くべきます。

あなたはおそらく必要なのは、あなたが、フェッチの使用、及びそれらが必要とされるような接続を返すことができ、接続プールです。

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
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top