首页 > 解决方案 > ActiveRecord MySQL 在查询期间丢失与 MySQL 服务器的连接

问题描述

我在生产中的 Rails 应用程序中连接到外部 AWS Aurora MySQL 时遇到问题。

这是设置:

在开发中,一切正常,但是当我部署到 Heroku 时,我只能成功查询外部数据库的一个表。当我创建另一个表时,我收到此错误消息:

ActionView::Template::Error (Mysql2::Error::ConnectionError: Lost connection
to MySQL server during query: SELECT `TMC_Identification`.`direction`,
`TMC_Identification`.`miles`, `TMC_Identification`.`road`, 
`TMC_Identification`.`tmc` FROM `TMC_Identification`) :
1: <%= raw(@tmcs.to_json) %> 

楷模:

class TmcReading < ApplicationRecord

  establish_connection(:tmc_data)
  self.table_name = "TMC_Readings"

end

class TmcIdentification < ApplicationRecord

  establish_connection(:tmc_data)
  self.table_name = "TMC_Identification"

end

数据库.yml:

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

production:
  <<: *default
  database: production
  username: admin
  password: <%= ENV['DATABASE_PASSWORD'] %>

tmc_data:
  adapter: mysql2
  encoding: utf8
  database: tmc_data
  username: <%= Rails.application.credentials.tmc_data_db[:username] %>
  password: <%= Rails.application.credentials.tmc_data_db[:password] %>
  host: tmc-data.cluster-ro-xyz.us-east-1.rds.amazonaws.com
  port: 3306

控制器动作

  def tmc_identifications

    @tmcs = TmcIdentification.all.select(:direction, :miles, :road, :tmc)

  end

看法

<%= raw(@tmcs.to_json) %>

在开发中一切正常,但在生产中却不行。相同的数据库和凭据在生产中用于“tmc_data”连接。

我假设我遇到了一些线程安全问题,但我不确定如何解决。

标签: mysqlruby-on-railsrubyactiverecord

解决方案


我解决这个问题的方法如下:

楷模:

class TmcData < ActiveRecord::Base
  self.abstract_class = true
  establish_connection(:tmc_data)
end

class TmcReading < ApplicationRecord
  self.table_name = "TMC_Readings"
end

class TmcIdentification < ApplicationRecord
  self.table_name = "TMC_Identification"
end

更多详情:https ://www.thegreatcodeadventure.com/managing-multiple-databases-in-a-single-rails-application/

此外,我停止使用我的开发和生产环境连接到同一个辅助数据库。


推荐阅读