Redis pub/sub on rails

前端 未结 1 1795
生来不讨喜
生来不讨喜 2020-12-29 09:38

Following the Redis Pub/Sub

this works fine and i can publish messages in any class using

$redis.publish \'channel\', { object: @object.id }
<         


        
相关标签:
1条回答
  • 2020-12-29 10:16

    The implementation of Redis#subscribe is a loop that will assume control of the current thread in order to listen to events. This means the boot process is halted when dropping a subscription into the context of a Rails class in the way you've shown.

    You could try wrapping the call in a thread, but this approach would literally create a new subscription each time this class loaded in a new process, like a rails console or multiple unicorns. Plus, you'd have to be careful about shared state and other threading issues. This is probably not what you want.

    You're best off starting a different process that loads the rails environment and subscribes to redis separately from the process(es) serving web requests. It could be a rake task like the following:

    namespace :subscribe do
      task :redis => :environment do
        $redis.subscribe("bravo") do |on|
          on.message do |channel, message|
            Rails.logger.info("Broadcast on channel #{channel}: #{message}")
            OtherClass.some_method # yada yada
          end
        end
      end
    end
    
    0 讨论(0)
提交回复
热议问题