【问题标题】:Custom database connections in Rails applicationRails 应用程序中的自定义数据库连接
【发布时间】:2014-12-24 09:30:57
【问题描述】:

我正在开发一个使用单个 PostgreSQL 数据库存储数据的 Rails 应用程序。然而,在应用程序的某些部分,我使用 WordNet - 一个英语 NLP 数据库。由于 NLP 分析会消耗大量资源,因此我将其放在单独的 PostgreSQL 实例中的不同服务器上,这样它就不会消耗我的 Web 服务器资源。对于未来,我也在考虑扩展这个数据库,但这是一个不同的故事。无论如何,通过这种配置,我有两台服务器和两个数据库:一个是 Rails 用于其模型的,另一个是包含大量数据的 NLP 数据库。

我的问题是:我应该在 Rails 应用程序的哪里与 NLP 数据库建立连接?目前,我已经将它放在了我的 config/environments/*.rb 文件中,它看起来像这样:

config.wordnet_connection = PG::Connection.new(host:'hostname',dbname:'dbname',user:'username',password:'password')

所以现在,在控制器中,当我需要访问 NLP 数据库时,我会使用以下代码:

conn = Rails.application.config.wordnet_connection
conn.exec(sql)

但是,当我将应用程序部署到我的生产服务器(使用 nginx+phusion 乘客)时,有时我会从控制器那里收到一条错误消息,试图从 wordnet_connection 获取一些数据:

控制器#action中的PG::UnableToSend

没有连接到服务器

此错误发生在以下行:

res = Rails.application.config.wordnet_connection.exec(sql)

我做错了什么?

【问题讨论】:

    标签: ruby-on-rails database postgresql


    【解决方案1】:

    将配置保存在一处database.yml

    production:
      adapter: postgresql
      other stuff...
    
    wordnet_connection:
      adapter: postgresql
      other stuff..
    
    other_envs:
    .....
    

    然后创建一个类

    class WordnetConnection < ActiveRecord::Base
      establish_connection(:wordnet_connection)
      self.table_name = "your_table"
    end
    

    然后你就可以像这样访问了

    WordnetConnection.first 
    

    我认为这会使备用数据库连接保持打开状态,这对性能来说可能是一件好事,也可以让您使用 AR

    在这里查看我的博客http://imnithin.github.io/multiple-database.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多