Rails 連接多個數據庫的兩種方式


有些時候,我的項目可以需要連接多個數據庫,這時應該怎么辦?我查閱了資料,大部分都是說在model里加入establish_connection來指向不同的數據庫,也有的說做個基礎的類,每個model繼承此類,這些說法都沒有錯,但不夠精練,我在此做個總結。

這里使用的是mysql和rails4.2

一、每個model各自連接

修改database.yml如下:

default: &default
  adapter: mysql2
  encoding: utf8
  pool: 5
  host: localhost
  username: username
  password: password
  database: databasename

development:
  <<: *default

test:
  <<: *default
  database: databasename_test

production:
  <<: *default
  database: databasename_production

others:
  development:
    adapter: mysql2
    encoding: utf8
    reconnect: true
    pool: 5
    host: localhost
    username: username
    password: password
    database: databasename2 
  production:
    adapter: mysql2
    encoding: utf8
    reconnect: true
    pool: 5
    host: localhost
    username: username
    password: password
    database: databasename2_production

創建一個module做數據庫連接,如下

  module DatabaseConnection

    def self.included(base)
        base.establish_connection DatabaseCnf[:others][Rails.env]   #DatabaseCnf是一個類,它用來讀取database.yml配置。
      end
  end

然后在每個需要這個連接的model里include這個module,就可以了,如:

  class Company < ActiveRecord::Base
    include DatabaseConnection
  end

這個Company類就可以連接到others下的數據庫的companies表了,操作和默認相同。

二、創建一個連接類,需要的可以繼承這個類

database.yml配置文件不變。

創建一個數據庫連接類:

class DatabaseConnection < ActiveRecord::Base
  self.abstract_class = true    #共用連接池,減少數據庫連接的消耗
  establish_connection DatabaseCnf[:others][Rails.env]  #DatabaseCnf是一個類,它用來讀取database.yml配置。
end

然后需要這個連接的model繼承這個類即可。

class Company < DatabaseConnection
end

這樣的Company就是使用的others下的數據庫的companies表了。

 

總結,我覺得使用第二種方式更好一些,它可以共享鏈接池,減少數據庫連接,降低系統資源的消耗。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM