【问题标题】:Ruby - Exception occured: [Mysql2::Error] closed MySQL connectionRuby - 发生异常:[Mysql2::Error] 关闭 MySQL 连接
【发布时间】:2012-07-31 05:10:51
【问题描述】:

我有一个 Rails 应用程序现在只在内部运行,所以现在没有那么多访问。并且有两个 resque 工作人员几乎不运行从 web 获取数据并插入到 mysql 数据库中,每个 insert 将随后休眠 10 秒。

我们在 VPS 上运行它。每隔 5 小时,我会遇到一个异常 Exception occured: [Mysql2::Error] closed MySQL connection"

导致异常的原因可能是什么?现在池大小为 5。

如果我提高池大小并在database.yml 中指定reconnect: true 会有帮助吗?

【问题讨论】:

    标签: mysql ruby-on-rails-3 resque


    【解决方案1】:

    这是结合多线程使用 mysql2 gem 版本 0.2.11 或更低版本时的常见问题。 a bug on the issue tracker 提供了有关问题的详细信息,但总而言之,建议是:

    1. 将您正在使用的 gem 版本更新为 >= 0.2.12
    2. database.yml 文件中添加reconnect: true 选项您的数据库连接配置

    您可能已经解决了您的问题,但这可能会对遇到此问题的其他人有所帮助。

    【讨论】:

    • reconnect: true 为我解决了这个问题。 (我已经在使用远高于 0.2.12 的版本。)
    【解决方案2】:

    如果您的工作人员长时间不活动,他们将失去 MySQL 连接。

    请参阅here 了解解决方案

    或者只是把它放在初始化器中

    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 
    

    【讨论】:

    • 嗨,约翰。发布此消息后,我将 pool 提高到 20 并将 reconnect: true 添加到我的 database.yml 中,它看起来已修复。我认为它和你建议的一样,是吗?
    【解决方案3】:

    更深入地了解如何为 delayed_job 进行调试。在database.yml 上设置reconnect: true 后,我做了以下操作,但此解决方案不起作用。

    cd /your_rails_deploy_code/log
    cat production.log
    
    # check the pids from delayed job:
    E, [2017-02-01T19:45:21.614579 #2592] ERROR -- : 2017-02-01T19:45:21+0000: [Worker(delayed_job.3 host:demeter pid:2592)] Job ActiveJob::QueueAdapters::DelayedJobAdapter::JobWrapper (id=193675) FAILED (0 prior attempts) with Mysql2::Error: closed MySQL connection
    

    在我的具体情况下,pid:2592 是唯一一个经常失败的。为什么?让我们找出答案:

    [deploy@demeter] ps -ef | grep 2592
    deploy   2592     1  0 Jan31 ?        00:00:40 production/delayed_job.3
    deploy   23312     1  0 Feb01 ?        00:00:40 production/delayed_job.1
    deploy   23318     1  0 Feb01 ?        00:00:40 production/delayed_job.0
    

    我注意到特定流程在我最近一次部署前几天就开始了。一旦我杀死它,错误就消失了。我假设在我的具体情况下发生的事情是我最新的部署没有正确删除所有延迟作业实例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 2013-08-13
      • 2021-03-17
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多