مشاركة اتصالات DB عبر الكائنات باستخدام طرق الفصل في Ruby؟

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

سؤال

أنا أكتب النصي الروبي لاستخدامه كإخلاء لسياسة الوصول إلى SMTP Postfix. يحتاج النص إلى الوصول إلى قاعدة بيانات Tyko Tyrant. أنا أستخدم EventMachine لرعاية اتصالات الشبكة. يحتاج EventMachine إلى فئة اتصال EventMachine :: إنشاء مثيل له حلقة معالجة EventMachine كلما تم إنشاء اتصال جديد. لذلك لكل اتصال يتم إنشاء فئة فئة ودمرتها.

أقوم بإنشاء اتصال Tokyo Tyrant من Post_init من EventMachine :: اتصال (أي اليمين بعد الاتصال هو الإعداد) وتمزيقه بعد انتهاء الاتصال.

سؤالي هو إذا كانت هذه هي الطريقة الصحيحة للاتصال 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 "*" }
}

فيما يتعلق،

راج

هل كانت مفيدة؟

المحلول

مفاجأة لا توجد إجابات على هذا السؤال.

ما تحتاجه هو بركة سباحة اتصال حيث يمكنك جلب الاتصالات واستخدامها وإرجاعها كما هي مطلوبة.

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