Redis + ActionController::Live threads not dying

前端 未结 6 1336
自闭症患者
自闭症患者 2020-11-28 04:09

Background: We\'ve built a chat feature in to one of our existing Rails applications. We\'re using the new ActionController::Live module and ru

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 04:20

    Building on @James Boutcher, I used the following in clustered Puma with 2 workers, so that I have only 1 thread created for the heartbeat in config/initializers/redis.rb:

    config/puma.rb

    on_worker_boot do |index|
      puts "worker nb #{index.to_s} booting"
      create_heartbeat if index.to_i==0
    end
    
    def create_heartbeat
      puts "creating heartbeat"
      $redis||=Redis.new
      heartbeat = Thread.new do
        ActiveRecord::Base.connection_pool.release_connection
        begin
          while true
            hash={event: "heartbeat",data: "heartbeat"}
            $redis.publish("heartbeat",hash.to_json)
            sleep 20.seconds
          end
        ensure
          #no db connection anyway
        end
      end
    end
    

提交回复
热议问题