ruby - 使用 ruby​​ 中的类方法跨对象共享数据库连接?

标签 ruby oop tokyo-cabinet eventmachine

我正在编写一个 ruby​​ 脚本,用作 Postfix SMTP 访问策略委托(delegate)。该脚本需要访问 Tokyo Tyrant 数据库。我正在使用 EventMachine 来处理网络连接。 EventMachine 需要一个 EventMachine::Connection 类,每当创建新连接时,该类由 EventMachine 的处理循环实例化。因此,对于每个连接,都会实例化并销毁一个类。

我正在从 EventMachine::Connection 的 post_init 创建到 Tokyo Tyrant 的连接(即在连接设置之后),并在连接终止后将其拆除。

我的问题是这是否是连接数据库的正确方法?即每次我需要时都建立连接并在完成后将其拆除?连接到数据库一次(当程序启动时)在程序关闭期间将其拆除不是更好吗?如果是这样,我应该如何编码?

我的代码是:

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

关于ruby - 使用 ruby​​ 中的类方法跨对象共享数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1253620/

相关文章:

tokyo-cabinet - 在 Eclipse 中使用 Tokyo Cabinet 的任何可能方法?

ruby-on-rails - 从现有表生成 activerecord 模式

java - 使用java激活html按钮

tokyo-cabinet - 为什么在调整bnum之后,东京暴君会成倍地减速?

api - Tokyo Cabinet 和 SQLite 兼容的接口(interface)吗?

c++ - 不使用 if 语句调用多个类

ruby datamapper 如何在查询中包含 has n association 的子关联

ruby-on-rails - Ruby on Rails has_many 多态

ruby - 如何在 pry 中运行带参数的文件

oop - 前端和后端之间的 DRY 原则