即使我的Rails应用程序中有50个池,我也编写了一个脚本,使用流行的守护进程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
但它似乎没有效果。
答案 0 :(得分:0)
我认为它与这个话题有关。 Connection pool issue with ActiveRecord objects in rufus-scheduler 简而言之,活动记录无法在线程之间共享连接池
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
希望这能指向正确的方向