[ruby on rails]同时链接多数据库

Rails6

  • database配置多个数据库
# 其他数据库默认配置
recommend_default: &recommend_default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  
# 生产可读数据库默认配置
prod_readonly_default: &prod_readonly_default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  replica: true #表示从库,只有读权限,不能写

development:
  primary:
    <<: *default
    database: web_development
  recommend:
    <<: *recommend_default
    database: web_recommend_development
  prod_readonly:
    <<: *prod_readonly_default
    database: web_readonly_development

  • 新建model链接只读库进行使用
# app/models/prod_readonly/prod_readonly_application_record.rb
class ProdReadonlyApplicationRecord < ActiveRecord::Base
  self.abstract_class = true

  connects_to database: { writing: :prod_readonly, reading: :prod_readonly }
end

# app/models/prod_readonly/readonly_user.rb
class ReadonlyUser < ProdReadonlyApplicationRecord
  self.table_name = 'users'
end

# 使用示例 join的orders也是只读库的orders表
ReadonlyUser.select('sum(price)').joins(:orders)  

Rails5

  • database.yml
default: &default
  encoding: utf8
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  wait_timeout: 60
  
oracle_development: #名字可自定义,但是不能重复。
  <<: *default
  adapter: oracle_enhanced
  host: xxx.xxx.xxx.xx
  username: root
  password: 123456
  database: oracle_dev
  port: 1521 # Oracle 的端口号,Mysql为3306,mysql一般不写 

mysql_development:
  <<: *default
  adapter: mysql2
  host: xxx.xxx.xxx.xx
  username: root
  password: 123456
  database: mysql_dev

第一种使用方法

  • 新建app/other_database_models/other_application.rb
class OtherApplication < ActiveRecord::Base #OtherApplication只是个名字,可随便定义
  self.abstract_class = true
  establish_connection :oracle_development # database.yml中配置的数据库
end
  • 新建app/other_database_models/user.rb
  • 使用oracle_development中的users表
class User < OtherApplication 
end

注意: 所有的models中名字不能重复,这里新建的user.rb不能在app/models中存在

第二种使用方法

  • 新建app/other_database_models/other_user.rb
class OtherUser < ActiveRecord::Base
  self.abstract_class = true
  establish_connection :oracle_development # database.yml中配置的数据库
  self.table_name = 'users' #申明使用的表
  
  def self.puts_time
  	put TIme.now
  end
end
  • 其他地方就可以调用
OtherUser.puts_time

第三种使用方法

  • 用db1前先链接db1, 用db2前先链接db2
# 链接db1
src_connection = ActiveRecord::Base.establish_connection(:oracle_development).connection
src_connection.active?
src_connection.exec_query(sql)
# 链接db2
production_connection = ActiveRecord::Base.establish_connection(:production).connection
production_connection.exec_query(sql)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值