Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Exception occured: [Mysql2::Error] closed MySQL connection

I have a Rails application now only runs internally, so there's not so much visits right now. And there're two resque worker running hardly to fetch data from the web and inserts into a mysql database, every insert will followed by sleep 10 second.

We run it on a VPS. After like every 5 hours, I will encounter an Exception Exception occured: [Mysql2::Error] closed MySQL connection".

What could be the reason causing the exception? Now the pool size is 5.

Will it help if I raise the pool size and specify reconnect: true in my database.yml?

like image 827
larryzhao Avatar asked Aug 02 '12 08:08

larryzhao


2 Answers

This is a common issue when using the mysql2 gem version 0.2.11 or below in combination with multithreading. There is a bug on the issue tracker with a details on the problem but in conclusion the advice is to:

  1. Update the gem version you are using to >= 0.2.12
  2. Add the reconnect: true option your db connection config in the database.yml file

You probably already solved your problem but this might help others who come across this question.

like image 60
Dirk Geurs Avatar answered Nov 13 '22 23:11

Dirk Geurs


If your workers are inactive for a long period of time, they'll lose their MySQL connection.

see here for the solution

or just stick this in an initializer

unless Rails.env.to_s == 'test'
  module ActiveRecord::ConnectionAdapters
    class Mysql2Adapter
      alias_method :execute_without_retry, :execute

    def execute(*args)
      execute_without_retry(*args)
      rescue Exception => e
        if e.message =~ /server has gone away/i
          warn "Server timed out, retrying"
          reconnect!
          retry
        else
          raise e
        end
      end
    end
  end
end 
like image 37
john.jansen Avatar answered Nov 13 '22 22:11

john.jansen