3

我有一个使用 Rack 的非常简单的 Web 服务,没有 Rails,我将在每个有效连接上联系 MySQL。我想保持连接(例如在构造函数中),以便在每次请求时我都重用它。让我们这样说:

  class Service

    def initialize(dbhost, dbport, dbname, dbuser, dbpass)
      @client = Mysql2::Client.new(
          :host => dbhost, 
          :port => dbport, 
          :database => dbname,
          :username => dbuser, 
          :password => dbpass)
    end

    def call(env)
       # some logic that will call:
       results = _query(sql)
    end

    def _query(sql)
      results = @client.query(sql)
    end

  end

  Rack::Handler::Mongrel.run Service.new(DB_HOST, DB_PORT, DB_NAME, DB_USER, DB_PASS), :Port => 8123  

使用上面的代码,该服务将获得一个 MySQL 连接,并在每个请求上进行查询。但是我如何确保如果连接断开,该_query方法将重新连接?

4

1 回答 1

5

好吧,:reconnect => true似乎可以确保连接保持不变。

  @client = Mysql2::Client.new(
      :host => dbhost, 
      :port => dbport, 
      :database => dbname,
      :username => dbuser, 
      :password => dbpass,
      :reconnect => true
      )
于 2012-11-07T08:36:55.060 回答