简体   繁体   English

Rails 应用程序中的自定义数据库连接

[英]Custom database connections in Rails application

I am working on a Rails app which uses a single PostgreSQL database for its data.我正在开发一个使用单个 PostgreSQL 数据库存储数据的 Rails 应用程序。 However, in some parts of the app I use WordNet - an NLP database of English.但是,在应用程序的某些部分,我使用 WordNet - 一个英语 NLP 数据库。 Since NLP analysis consumes a lot of resources, I put it on a different server in a separate PostgreSQL instance so it wouldn't consume my web server resources.由于 NLP 分析会消耗大量资源,因此我将其放在单独的 PostgreSQL 实例中的不同服务器上,这样它就不会消耗我的 Web 服务器资源。 For the future I am also considering scaling this database, but it's a different story.对于未来,我也在考虑扩展这个数据库,但这是一个不同的故事。 Anyway, with this configuration, I have two servers and two databases: the one that Rails uses for its models, and a second one - the NLP database with a lot of data.无论如何,通过这种配置,我有两台服务器和两个数据库:一个是 Rails 用于其模型的,另一个是 - 包含大量数据的 NLP 数据库。

My question is: where exactly in the Rails app should I establish a connection with the NLP database?我的问题是:我应该在 Rails 应用程序中的哪个位置与 NLP 数据库建立连接? Currently, I've put it inside my config/environments/*.rb files, and it looks like this:目前,我已经把它放在我的 config/environments/*.rb 文件中,它看起来像这样:

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

So now, in the controllers, when I need access to NLP database I use this code:所以现在,在控制器中,当我需要访问 NLP 数据库时,我使用以下代码:

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

However, when I deployed the app to my production server (using nginx+phusion passenger) sometimes I get an error message from the controllers which try to get some data from wordnet_connection:但是,当我将应用程序部署到我的生产服务器(使用 nginx+phusion 乘客)时,有时我会从试图从 wordnet_connection 获取一些数据的控制器收到一条错误消息:

PG::UnableToSend in Controller#action PG::UnableToSend 在控制器中#action

no connection to the server没有连接到服务器

This error happens on the following line:此错误发生在以下行:

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

What am I doing wrong?我究竟做错了什么?

keeping the configurations at one place database.yml将配置保存在一个地方database.yml

production:
  adapter: postgresql
  other stuff...

wordnet_connection:
  adapter: postgresql
  other stuff..

other_envs:
.....

Then create a class然后创建一个类

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

Then you can access just like然后你可以访问就像

WordnetConnection.first 

I think this keeps the alternate database connection open which could be a good thing for performance as well also allows you to use AR我认为这可以保持备用数据库连接打开,这对性能来说可能是一件好事,也允许您使用 AR

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM