我有一个非常简单的使用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
方法将重新连接?
答案 0 :(得分:4)
好吧,:reconnect => true
似乎确保连接是持久的。
@client = Mysql2::Client.new(
:host => dbhost,
:port => dbport,
:database => dbname,
:username => dbuser,
:password => dbpass,
:reconnect => true
)