2014-08-11 13:13:37 +08:00
|
|
|
|
2015-04-25 04:22:24 +08:00
|
|
|
if Rails.version >= "4.2.0"
|
2014-10-25 17:37:57 +08:00
|
|
|
class ActiveRecord::ConnectionAdapters::AbstractAdapter
|
|
|
|
module LastUseExtension
|
2016-04-01 05:33:25 +08:00
|
|
|
attr_reader :last_use, :first_use
|
2014-10-25 17:37:57 +08:00
|
|
|
|
|
|
|
def initialize(connection, logger = nil, pool = nil)
|
|
|
|
super
|
|
|
|
@last_use = false
|
2016-04-01 05:33:25 +08:00
|
|
|
@first_use = Time.now
|
2014-10-25 17:37:57 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def lease
|
|
|
|
synchronize do
|
|
|
|
unless in_use?
|
|
|
|
@last_use = Time.now
|
|
|
|
super
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2014-08-11 13:13:37 +08:00
|
|
|
|
2014-10-25 17:37:57 +08:00
|
|
|
prepend LastUseExtension
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
class ActiveRecord::ConnectionAdapters::ConnectionPool
|
2014-08-11 13:13:37 +08:00
|
|
|
# drain all idle connections
|
|
|
|
# if idle_time is specified only connections idle for N seconds will be drained
|
2016-04-01 05:33:25 +08:00
|
|
|
def drain(idle_time=nil, max_age=nil)
|
2014-08-11 13:13:37 +08:00
|
|
|
synchronize do
|
|
|
|
@available.clear
|
|
|
|
@connections.delete_if do |conn|
|
2016-04-01 05:33:25 +08:00
|
|
|
try_drain?(conn, idle_time, max_age)
|
2014-08-11 13:13:37 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
@connections.each do |conn|
|
|
|
|
@available.add conn if !conn.in_use?
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2016-04-01 05:33:25 +08:00
|
|
|
def try_drain?(conn, idle_time, max_age)
|
2014-08-11 13:13:37 +08:00
|
|
|
if !conn.in_use?
|
2016-04-01 05:33:25 +08:00
|
|
|
if !idle_time || conn.last_use < idle_time.seconds.ago || (max_age && conn.first_use < max_age.seconds.ago)
|
2014-08-11 13:13:37 +08:00
|
|
|
conn.disconnect!
|
|
|
|
return true
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
false
|
|
|
|
end
|
|
|
|
end
|