How to persist mysql connection (mysql2 gem) with Ruby (no RoR)
mysql2, rack, ruby
Solution
Well, `:reconnect => true` seems to ensure that the connection is persisted.
@client = Mysql2::Client.new(
:host => dbhost,
:port => dbport,
:database => dbname,
:username => dbuser,
:password => dbpass,
:reconnect => true
)
Problem
I have a very simple web service using Rack, without Rails that I will contact MySQL on every valid connection. I want to persist the connection (for example in the constructor), so that on every request I reuse it. Lets say something like this: ``` 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 ``` With the code above, the service will obtain a MySQL connection and on every request it will do a query. But how do I make sure that if the connection drops, the `_query` method will reconnect?