如何在ActiveRecord中重用连接?

mrr*_*sof 5 ruby activerecord sinatra

当我发现这个简单的API没有自动重用连接时,我正在玩Sinatra和ActiveRecord.

#!/usr/bin/env ruby                                                                                  

require 'sinatra'
require 'active_record'

ActiveRecord::Base.establish_connection(
adapter:  'sqlite3',
database: 'newsletter.db'
)

ActiveRecord::Schema.define do
  create_table :subscribers do |t|
    t.string :email
    t.timestamps
  end
end

class Subscriber < ActiveRecord::Base
  validates :email, presence: true
end

class Newsletter < Sinatra::Base

  set :server, :thin

  get '/subscribers/:email' do
    s = Subscriber.find_by_email(params[:email])
    if s == nil
      status 404
    else
      content_type 'application/json'
      s.to_json
    end
  end

  post '/subscribers/:email' do
    Subscriber.create(email: params[:email])
  end

end

Newsletter.run!
Run Code Online (Sandbox Code Playgroud)

API在前5次订阅用户时返回订户或404.我第六次超时了.在前5个GET中的每一个之后,还有一个读取/写入文件描述符打开newsletter.db.我希望一直只有一个.

如何告诉ActiveRecord重用连接?

mrr*_*sof 1

ActiveRecord::Base.clear_active_connections!清理连接的一种方法是在每次使用Subscriber.find_by_email和后调用Subscriber.create,如下所示。

after do
    ActiveRecord::Base.clear_active_connections!
end
Run Code Online (Sandbox Code Playgroud)

在其他地方,有些人建议使用中间件ActiveRecord::ConnectionAdapters::ConnectionManagement。这在 Thin 中不起作用,因为 Thin 开始在一个线程中处理每个请求,并在另一个线程中完成处理该请求。ConnectionManagement仅将当前线程处于活动状态的连接返回到池中,并且 Thin 适用ConnectionManagement于第二个线程而不是第一个线程。

编辑:

我解释了为什么使用中间件ActiveRecord::Connectionadapters::ConnectionManagement不能在线程模式下与 Thin 一起使用,您可以在此处找到。

2016.05.18 编辑:

我向 Thin 作者跟进了这个问题,但在问题307之后这个问题没有得到解决。