mysql - ActiveRecord MySQL 在查询期间丢失与 MySQL 服务器的连接
问题描述
我在生产中的 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) %>
- 导轨 5.2
- 红宝石 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
控制器动作
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/
此外,我停止使用我的开发和生产环境连接到同一个辅助数据库。
推荐阅读
- sapui5 - 在 sap.m.list 行中添加按钮
- sql - sql中没有循环的均匀分布
- javascript - css 动画 - 将元素从其位置缩放到中心
- angular - 将 HTML 片段附加到 Angular 6 中的视图
- windows - 如何使用 Perl 在其他平台上执行在 WINdows 上创建的 .exe 文件
- javascript - GET 请求 - 如何存储数据。
- .net - 无法从 Azure 连接到 Nexmo API
- php - 多维数组求和并根据键值放入单列
- mysql - 如何获得具有所需输出的数据透视类型
- docker - 如何通过 SSH 连接到由快速启动终端创建的 docker 机器?