繁体   English   中英

Rails应用程序用尽数据库连接

[英]rails application running out of database connections

即使我的Rails应用程序中有50个池,我也编写了一个脚本,该脚本使用流行的daemons gem定期处理任务。 看起来是这样的:

class Responder
  def initialize
    @queue = Queue.new
  end
  # add to queue
  def produce(msg)
    @queue << msg
  end

  # take from queue
  def consume
    Thread.new do

      loop do
        sleep(1)
        if !@queue.empty?
          data = @queue.pop
          process(data)
        end
      end

    end 
  end
end

class EmailResponder < Responder
  def process(message)
    Alert.where(id: message[:id]).send_mail 
  end
end

class GeocodeResponder < Responder
  def process(message)
    Report.where(id: message[:id]).geocode_data
  end
end

class RedisListener
  def initialize(host,port)
    @host = host
    @port = port
    @email_sms = EmailResponder.new
    @geocode = GeocodeResponder.new
    # timeout so we wait for messages forever
    @redis = Redis.new(:host => @host, :port => @port, :timeout => 0)
  end

  def start_producers
    thread = Thread.new do
      @redis.subscribe('juggernaut') do |on|
        on.message do |event, msg|
          @email_sms.produce(msg)
          @geocode.produce(msg)
        end
      end
    end
  end

  def start_consumers
      @email_sms.consume
      @sidekiq.consume
  end
end

  listener = RedisListener.new('127.0.0.1', 6379)
  listener.start_producers
  listener.start_consumers

问题是很多项目都通过redis传递,因此队列建立了起来,最终我使用了越来越多的数据库连接,以至于达到postgresql max连接时崩溃。 我不想限制队列的大小,否则我可能会丢失动态丢失的数据。 我宁愿让队列增长,也要实际上限制数据库连接。 如何在此Rails守护程序中限制数据库连接(因此,当我使用Alert.where(...)或Report.where(...)之类的ActiveRecord对象时,它将阻塞直到数据库连接免费为止)?

我尝试将其添加到脚本中:

ActiveRecord::Base.configurations['production']['pool'] = 10

但这似乎没有效果。

我认为它与此主题有关。 rufus-scheduler中ActiveRecord对象的连接池问题简而言之,活动记录无法在线程之间共享连接池

def handle_db_pools(&block)
  ActiveRecord::Base.connection_pool.with_connection &block
end

handle_db_pools do
  Alert.where(id: message[:id]).send_mail 
end

希望这能为您指明正确的方向

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM