从线程中捕获未定义的方法异常并在ruby中重新启动它

时间:2015-06-29 14:58:45

标签: ruby multithreading exception-handling activemq stomp

我在ruby中有一个activemq主题订阅者,它使用带故障转移的stomp协议连接到代理,如果以某种方式重新启动activemq,那么有时我会得到一个异常:

undefined method `command' for nil:NilClass
/usr/lib64/ruby/gems/1.8/gems/stomp-1.1.8/lib/stomp/client.rb:295:in `start_listeners'
/usr/lib64/ruby/gems/1.8/gems/stomp-1.1.8/lib/stomp/client.rb:108:in `join'
/usr/lib64/ruby/gems/1.8/gems/stomp-1.1.8/lib/stomp/client.rb:108:in `join'
./lib/active_mq_topic_reader.rb:31:in `active_mq_topic_reader'
main.rb:164
main.rb:163:in `initialize'    
main.rb:163:in `new'

但是只有当我在代理线程上使用join()方法时才会出现此异常,否则不会出现异常,订阅者将从主题中取消订阅。 我面临的问题是我有一种不同的机制,通过发送关闭信号关闭进程,直到那时进程等待,但如果我们使用join()然后进程将卡在这一行,我将不会能够通过关闭信号关闭方法。那么我该怎么做才能捕获异常并重新启动监听器线程?

active_mq_topic_reader.rb:

require 'rubygems'
require 'ffi-rzmq'
require 'msgpack'
require 'zmq_helper'
require 'stomp'

include ZmqHelper

def active_mq_topic_reader(context, notice_agg_fe_url, signal_pub_url, monitor_url, active_mq_broker, topic)
  begin
    sender = create_connect_socket(context, ZMQ::PUSH, notice_agg_fe_url)
    monitor = create_connect_socket(context, ZMQ::PUSH, monitor_url)
    active_mq_broker.subscribe(topic, {}) do |msg|
        notice = {}
        ["entity_id","entity_type","system_name","change_type"].each do |key|
            notice[key] = msg.headers[key].to_s
        end
    monitor.send_string("qreader-#{topic.slice(7..-1)}")
    sender.send_string(notice.to_msgpack)
    end
active_mq_broker.join()  #cannot use this
    signal_subscriber.recv_string() #here the code waits for shutdown signal in case of process shutdown
    sender.close()
    monitor.close()
    signal_subscriber.close()
    active_mq_broker.unsubscribe(topic)
    return
  rescue Exception => e
    puts "#{topic}: #{e}"
    puts e.backtrace
    $stdout.flush
  end
end

main.rb:

context = ZMQ::Context.new(1)
active_mq_broker_audit = Stomp::Client.new("failover:(stomp://localhost:61613,stomp://localhost:61613)")
new_thread = Thread.new do
  active_mq_topic_reader(context,
                         "inproc://notice_agg_fe",
                         "inproc://signal_pub",
                         "tcp://localhost:xxxx",
                         active_mq_broker_audit,
                         "/topic/myTopic")
end
new_thread.join()

0 个答案:

没有答案