简体   繁体   中英

How to create a new ActiveRecord Connection Pool with Ruby on Rails?

I have a RoR app that works great with the main RoR database. I also want to connect to arbitrary databases in a way such that I won't recreate the database connection with each new HTTP request. From my research it looks like a connection pool is the way to go.

However, I am having trouble figuring out how to create the pool itself:

config = ActiveRecord::ConnectionAdapters::ConnectionSpecification.new( {
          "adapter"  => "postgresql",
          "host"     => "localhost",
          "port"     => 9000,
          "database" => "foo_test",
          "username" => "foo",
          "password" => "bar",
          "pool"     => "5",
          "timeout"  => "3000"
        })

my_connection_pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new(config)

This errors with NameError: uninitialized constant ActiveRecord::ConnectionAdapters::ConnectionSpecification. Interstingly ActiveRecord::ConnectionAdapters::ConnectionPool works fine (but doesn't have the right config object).

What do I do here?

And also, are these the right things to be using to solve my problem?

Depending on your use case, Rails might do this for you automatically. Each ActiveRecord::Base subclass looks up the inheritance chain to find its pool, so

class Foo < ActiveRecord::Base
end

Uses the ActiveRecord::Base connection pool, but

class Bar < ActiveRecord::Base
  establish_connection database: 'some_other_db'
end

class BarSub < Bar
end

would both connect to 'some_other_db' using the Bar pool.

I don't remember exactly, but I think every time you use ActiveRecord::Base.establish_connection (or establish_connection on any subclass) it creates a new pool. Doing otherwise would be absurd!

A possibly helpful SO post on establish_connection

I just have a separate file in my initializers that i use to create multiple connection with. The lib file is :

require 'active_record'

module whateverName

  def self.included(klass)
    klass.extend(ClassMethods)
  end

  module ClassMethods
    def base(dbName)
      establish_connection(ActiveRecord::Base.configurations[dbName.to_s][Rails.env])
    end
  end

end

Keep that file in lib and in models just include this and pass the database type. Make sure database.yml has the required configurations. Model will be something like :

class Bar < ActiveRecord::Base
  include whateverName
  base :oracle
end

All you need to have is a config for oracle in database.yml.

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