简体   繁体   中英

Custom database connections in Rails application

I am working on a Rails app which uses a single PostgreSQL database for its data. However, in some parts of the app I use WordNet - an NLP database of English. 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. 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.

My question is: where exactly in the Rails app should I establish a connection with the NLP database? Currently, I've put it inside my config/environments/*.rb files, and it looks like this:

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:

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:

PG::UnableToSend in Controller#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

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

Check my blog here http://imnithin.github.io/multiple-database.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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