【问题标题】:Rails: switch connection on each request but keep a connection poolRails:在每个请求上切换连接,但保留一个连接池
【发布时间】:2013-05-27 14:58:02
【问题描述】:

在我们的 Rails 应用程序中,我们需要根据请求的子域使用不同的数据库(每个国家/地区不同的数据库)。

现在我们正在做类似于this question 中建议的事情。也就是说,在每个请求上调用ActiveRecord::Base.establish_connection

但是it seemsActiveRecord::Base.establish_connection会丢弃当前的连接池,每次调用都会建立一个新的连接。

我做了这个快速基准测试,看看每次调用 establish_connection 和已经建立连接之间是否有任何显着差异:

require 'benchmark/ips'

$config = Rails.configuration.database_configuration[Rails.env]
$db1_config = $config.dup.update('database' => 'db1')
$db2_config = $config.dup.update('database' => 'db2')

# Method 1: call establish_connection on each "request".
Benchmark.ips do |r|
  r.report('establish_connection:') do
    # Simulate two requests, one for each DB.
    ActiveRecord::Base.establish_connection($db1_config)
    MyModel.count # A little query to force the DB connection to establish.
    ActiveRecord::Base.establish_connection($db2_config)
    MyModel.count
  end
end

# Method 2: Have different subclasses of my models, one for each DB, and 
# call establish_connection only once
class MyModelDb1 < MyModel
  establish_connection($db1_config)
end

class MyModelDb2 < MyModel
  establish_connection($db2_config)
end

Benchmark.ips do |r|
  r.report('different models:') do
    MyModelDb1.count
    MyModelDb2.count
  end
end

我用rails runner 运行这个脚本,并指向一个本地mysql,数据库上有几千条记录,结果似乎表明两者之间实际上存在很大差异(一个数量级)方法(顺便说一句,我不确定基准是否有效或我搞砸了,因此结果具有误导性):

Calculating -------------------------------------
establish_connection: 8 i/100ms
-------------------------------------------------
establish_connection: 117.9 (±26.3%) i/s -        544 in   5.001575s
Calculating -------------------------------------
    different models:  119 i/100ms
-------------------------------------------------
    different models:  1299.4 (±22.1%) i/s -       6188 in   5.039483s

所以,基本上,我想知道是否有办法为每个子域维护一个连接池,然后重新使用这些连接,而不是在每个请求上建立一个新连接。为每个子域设置我的模型的子类是不可行的,因为有很多模型;我只想更改所有模型的连接(ActiveRecord::Base

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    嗯,我已经对此进行了深入研究,并设法使某些东西发挥作用。

    在阅读 tenderlove's post 关于 ActiveRecord 中的连接管理(它解释了类层次结构如何与连接管理不必要地耦合)之后,我明白了为什么我想做的事情不像人们期望的那样简单。

    我最终做的是继承 ActiveRecord 的 ConnectionHandler 并在我的模型层次结构的顶部使用新的连接处理程序(需要对 ConnectionHandler code 进行一些摆弄以了解它在内部是如何工作的;所以当然这个解决方案可能与我正在使用的 Rails 版本(3.2)非常相关)。比如:

    # A model class that connects 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
    
    # ...
    
    class CustomConnectionHandler < ActiveRecord::ConnectionAdapters::ConnectionHandler
      def initialize
        super
        @pools_by_subdomain = {}
      end
    
      # Override the behaviour of ActiveRecord's ConnectionHandler to return a
      # connection pool for the current domain.
      def retrieve_connection_pool(klass)
        # Get current subdomain somehow (Maybe store it in a class variable on 
        # each request or whatever)
        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 receives a key 
        # (in this case the subdomain) for the new connection pool
        establish_connection(subdomain, resolver.spec)
      end
    end
    

    这仍然需要一些测试来检查是否确实有性能提升,但我在本地 Unicorn 服务器上运行的初始测试表明确实有。

    【讨论】:

    • @MikeCampbell,我在实现这个时没有遇到这个问题。该解决方案适用于具有十几个子域而不是数百个子域的站点,并且预计该数字不会增长。如果您需要控制连接数,也许您可​​以使用其他一些数据结构来存储连接池,例如具有最大大小的 LRU 缓存。
    • @Rubytastic 我没有在 Rails 4 中尝试过。这些类的内部结构是否发生了变化?如果他们这样做了,我强烈建议您首先检查重复使用连接的这种技巧是否仍然有意义。也许它不再有任何意义了。
    • @epidemian 你知道@pools_by_subdomain 的生命周期是多久吗?它会在每个请求(如控制器实例变量)时重置还是在应用程序生命周期内保持不变?谢谢
    • @Vbp 它的生命周期与分配给 ModelBase.connection_handlerCustomConnectionHandler 的生命周期一样长,这应该是应用程序/进程的生命周期,除非它被重新分配到其他地方:)
    【解决方案2】:

    据我所知Rails 不会在请求之间维护它的数据库池,除非您使用多线程环境。像 Sidekiq。但是如果您在生产服务器上使用Passenger 或Unicorn,它将为每个Rails 实例创建一个新的数据库连接。

    所以基本上使用数据库连接池是没有用的,这意味着在每个请求上创建一个新的数据库连接不应该是一个问题。

    【讨论】:

    • 有趣;也许我正在尝试解决一个没有问题的问题= P。你有这个信息的指针吗?我已经运行的基本测试(基本上是一个 cURL 请求循环使用不同的子域(即不同的数据库)访问网络服务器(独角兽))表明,当保持连接池处于活动状态时,延迟显着减少。
    • 致匿名投票者:请告诉我们为什么此答案中的信息没有帮助。
    • 独角兽主进程持有连接池,当工作者启动时,工作者从该连接池中签出连接。见devcenter.heroku.com/articles/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 2023-04-06
    • 2023-02-01
    相关资源
    最近更新 更多