开发者

MySQL connection timeout - MySQL server has gone away (Sinatra, ActiveRecord)

Here is an outline of my app:

require 'sin开发者_如何学JAVAatra'
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!


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


You're probably encountering the same issue as is covered by this other SO question: "MySQL server has gone away" with Ruby on Rails


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜