Environment: ruby 2.1.3, rails 4.2, activaterecord-sqlserver-adapter 4.1
If you have to switch from place to place to place to process 20 databases.
First, prepare an array (specs) containing connection information and
Benchmark.bm do|x|
100.times {x.report{ActiveRecord::Base.establish_connection(specs.sample)}}
end
I checked and found out.It seems to take 0.9 to 1.2 seconds.
Regardless of the cost of a single unit, first keep all the connections and
Would it be possible to reduce the switching cost by changing only where the query is thrown?
Here's what I'm thinking:
(I also thought about creating a DB connection model and inheriting each model.I also find it strange to make 20 copies of each model file.I thought about dynamically replicating and re-inheriting the model, but I want to use it as a last resort.and)
I've never actually done it myself, and there are some differences from the situation you asked, but I thought the content of this page was quite close.
Code quoted from the above article
#A model class that connections to a different DB depending on the subdomain
# we're in
class ModelBase<ActiveRecord::Base
self.abstract_class = true
self.connection_handler=CustomConnectionHandler.new
end
# ...
classCustomConnectionHandler<ActiveRecord::ConnectionAdaptors::ConnectionHandler
def initialize
super
@pools_by_subdomain={}
end
# Override the behavior of ActiveRecord's ConnectionHandler to return a
# connection pool for the current domain.
default_connection_pool(kclass)
# Get current subdomain somehow (Maybe store it in a class variable on)
# each request or whatver)
subdomain=@@subdomain
@ pools_by_subdomain [subdomain]||=create_pool(subdomain)
end
private
def create_pool(subdomain)
conf=Rails.configuration.database_configuration [Rails.env].dup
# The name of the DB for that subdomain...
conf.update!('database'=>"db_#{subdomain}")
resolver=ActiveRecord::Base::ConnectionSpecification::Resolver.new(conf,nil)
# Call ConnectionHandler #establish_connection, which receipts a key
# (in this case the subdomain) for the new connection pool
establish_connection(subdomain,resolver.spec)
end
end
The original article requires that the connection be changed according to the subdomain, and the connection is switched within the retrieve_connection_pool
method.
If you change this area to fit your requirements, you may be able to achieve your goal.
That's all for your information.
© 2024 OneMinuteCode. All rights reserved.