views:

893

answers:

4

Hi,

Here is an outline of my app:

require 'sinatra'
require 'active_record'

ActiveRecord::Base.establish_connection(
     :adapter => "mysql", host => $DB_HOSTNAME,
     :database => $DB_NAME,:username => $DB_USERNAME,:password => $DB_PASSWORD)

class Sometable < ActiveRecord::Base
end

get '/' do
  #stuff with Sometable
end

# a lot of route handlers..

etc.

I call *establish_connection* just once - during the app initialization. I encountered the 8 hour idle connection limit of MySQL (MySQL server has gone away) and am wondering the best approach to it.

I went through ActiveRecord source and found that it pools db server connections. So, should I ideally create a new connection inside every web request or increase the timeout setting?

Thanks for your time!

+1  A: 

You could increase the wait_timeout variable for mysqld. It can be set in config file or passed by command line args.

Are you using persistent connections?

One other thing to try is to have the mysql client set MYSQL_OPT_RECONNECT

Sean A.O. Harney
+1  A: 

You're probably encountering the same issue as is covered by this other SO question: http://stackoverflow.com/questions/100631/mysql-server-has-gone-away-with-rails

Pete Hodgson
+1  A: 

I had a similar problem suddenly start (in some C++ code) when mySQL was upgraded.

This was because the auto reconnect is set by default to 0 in version 5.0.3 (http://dev.mysql.com/doc/refman/5.0/en/mysql-options.html).

I had to set MYSQL_OPT_RECONNECT to "1" in the code.

Note: it should be called after any mySQL init() calls and before making the actual connection.

aiGuru
A: 

Thanks for all the answers. MYSQL_OPT_RECONNECT seems to be a good solution. But I'm not sure how to do it using ActiveRecord.

For now, I've solved it using:

#prevent MySQL server has gone away by verifying connections every 30 minutes.
Thread.new { 
  loop {
    sleep(60*30);
    ActiveRecord::Base.verify_active_connections!
  }
}.priority = -10
Jasim