rails 5.0.7 如何获取数据库中可用的数据连接数和已使用的线程数,需要把这个两个参数实时监控起来
如果你是指的 active_record 的连接池 connection_pool 的话,在源码 https://github.com/rails/rails/blob/v5.0.7/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb#L345 里。
@connections
存了当前进程从数据库获取到的总连接;
@available
存@connections
中空闲的,可分配给线程的连接;
@thread_cached_conns
是个 hash,存了@connections
中已分配给线程的连接。
# rails c例子
# 连接池最多可以有多少个连接
ActiveRecord::Base.connection_pool.instance_eval { @size }
# 连接池目前已经从数据库获得了多少个连接
ActiveRecord::Base.connection_pool.instance_eval { @connections.size }
# 当前线程占用一个连接
User.first
ActiveRecord::Base.connection_pool.instance_eval { @connections.size }
# 新起一个线程,又占用一个连接
Thread.new {User.first; sleep}
ActiveRecord::Base.connection_pool.instance_eval { @connections.size }
# 查看每个线程占用的连接
ActiveRecord::Base.connection_pool.instance_eval { @thread_cached_conns.keys }
# 释放当前线程的连接
ActiveRecord::Base.connection_pool.release_connection
ActiveRecord::Base.connection_pool.instance_eval { @connections.size }
ActiveRecord::Base.connection_pool.instance_eval { @available.instance_eval{@queue.size} }
如果你是指数据库当前本身有多少个连接的话,mysql 的话,我查到是如下的 sql
ActiveRecord::Base.connection.exec_query("show status where `variable_name` = 'Threads_connected';")
Agenter is an Online Professional Networking Platform for Commission, where business profiles present their sales requirements on a commission basis and offer a new way of employment opportunities to every common man and sales agent, to connect and earn a commission. For more information commission based business in india