由于需要在 Rails 项目中监听 MQTT 所有的事件进行处理,于是在 config/initializers/mqtt.rb
中定义了以下代码,但是总是无法获取到线程中的实例,请教问题在哪?
require 'mqtt'
require 'logger'
require 'mqtt_event_handler'
mqtt_config = Rails.application.config_for(:mqtt).symbolize_keys
mutex = Mutex.new
resource = ConditionVariable.new
Thread.new do
mutex.synchronize do
mqtt_config.merge!(client_id: "#{Rails.env.upcase}#{Thread.current.object_id}")
begin
@client = MQTT::Client.connect(mqtt_config)
topics = ['#']
@client.subscribe(*topics)
resource.broadcast
resource.wait(mutex)
@client.get do |t, m|
MQTTEventHandler.call(t, m)
end
rescue MQTT::ProtocolException => error
Logger.error error.message
end
end
end
thread = Thread.new do
mutex.synchronize do
Thread.current[:client] = @client
puts Thread.current[:client] #> #<MQTT::Client:0x007fda10245e90>
resource.signal
end
end
puts thread[:client] #> nil