CppNoob
CppNoob

Reputation: 2400

Rails4: How can I get the number of idle connections in an ActiveRecord connection pool?

I can see a stat method defined for Rails 5 (http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html#method-i-stat). This reports connections in various states. This is not available in Rails 4 or earlier. Is there an alternative way to get the information in Rails 4?

Upvotes: 0

Views: 570

Answers (1)

jon snow
jon snow

Reputation: 3072

You can patch same that method star in Rails4

This is something you can add in Rails-4 also.

ActiveRecord::Base.connection_pool.synchronize do
  { connections: ActiveRecord::Base.connection_pool.connections.size }
end

=> {:connections=>1}

Rails5 stat definition

# File activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb, line 583
def stat
  synchronize do
    {
      size: size,
      connections: @connections.size,
      busy: @connections.count { |c| c.in_use? && c.owner.alive? },
      dead: @connections.count { |c| c.in_use? && !c.owner.alive? },
      idle: @connections.count { |c| !c.in_use? },
      waiting: num_waiting_in_queue,
      checkout_timeout: checkout_timeout
    }
  end
end

Upvotes: 1

Related Questions