lundi 29 août 2016

Rails and MQTT: Subscribe to topic in background at server startup?

I want to subscribe to a mqtt topic in my rails app when the server starts and and keep the subscription always active and running.

I'm using this mqtt gem for mqtt communication: http://ift.tt/1ABvDRN

Here is what I have right now:

in application.rb:

config.after_initialize do
 mqttSub = BackgroundMQTT.new
 mqttSub.run
end

BackgroundMQTT class:

class MQTTSubscriber
  def run
    Thread.new do
      MQTT::Client.connect(:host => 'localhost', :port => 1883,) do |c|
        c.get('#') do |topic,message|
          puts "#{topic}: #{message}"
          #Do things, access activerecord etc.
        end
      end
    end
  end
end

So basically the mqtt subscription starts in the after_initialize method and as far as I know, doesn't stop automatically?

Also As you can see, I'm running the subscription in a Thread, otherwise my rails application would stop doing anything else than listening to the mqtt subscription.

This seems to work at least for the first couple of minutes.

I'm not sure if this is a recommended way of doing what I want to do. Could this cause any issues that I haven't considered? What would be a recommend way of doing this?

Aucun commentaire:

Enregistrer un commentaire