mysql - ActiveRecord MySQL 在查询期间丢失与 MySQL 服务器的连接

标签 mysql ruby-on-rails ruby activerecord

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

这是设置:

  • 应用的一个主要 PostgreSQL 数据库
  • 一个外部 (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) %> 
  • Rails 5.2
  • ruby 2.5.3

型号:

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

Controller 操作

  def tmc_identifications

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

  end

查看

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

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

我认为我遇到了一些线程安全问题,但我不知道如何解决这个问题。

最佳答案

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

型号:

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/

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

关于mysql - ActiveRecord MySQL 在查询期间丢失与 MySQL 服务器的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53579858/

相关文章:

java - 通过jsp更新数据库表到jsp

ruby-on-rails - Coffeescript 访问 current_user

ruby-on-rails - rails : Route to custom controller action

ruby-on-rails - sidekiq Ruby 脚本后 Postgres 连接未关闭

ruby-on-rails - 将集合和自定义字段添加到选择框

ruby-on-rails - Ruby:Declarative_authorization 多态关联

PHP PDO和mysql无法选择带字母的id

mysql - 获取从当月第 n 个日期到下一个第 n 个日期的行

MySQL - Group By, Max, Inner Join - 问题

ruby-on-rails - 对关联进行彻底搜索并拒绝