Skip to content

Instantly share code, notes, and snippets.

@hassox
Forked from careo/disconnect.rb
Created February 18, 2010 00:17
Show Gist options
  • Save hassox/307177 to your computer and use it in GitHub Desktop.
Save hassox/307177 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'mq'
class ConnectionManager
@@current_connection = :default
@@alternative_connections = [:default, :default1, :default2]
def self.connections(type = :deafult)
# To connect to different nodes, have a configuration hash
# that matches the type, and use that for differnt connections
#
# CAn use this method to cycle through alternai
@connections ||= Hash.new do |h,k|
conn = AMQP.connect
conn.callback{ do_setup }
h[k] = conn
end
@connections[type]
end
def self.connection
connections @@current_connection
end
def self.reconnect
idx = @@alternative_connections.index(@@current_connection)
idx = idx >= (@@alternative_connections.size - 1) ? 0 : (idx + 1)
@@current_connection = @@alternative_connections[idx]
puts "Reconnecting on #{@@current_connection.inspect}"
connection.reconnect
end
end
EM.error_handler {|e|
p [:exception, e, e.backtrace.first]
if e.kind_of? AMQP::Error
EM.add_timer(1) {
ConnectionManager.reconnect
}
end
}
def do_setup
p [:do_setup]
mq = MQ.new(ConnectionManager.connection)
mq.queue("test").subscribe { |msg|
p "Received: #{msg}"
}
EM.add_periodic_timer(1) do
mq.queue('test').publish("Hey - #{Time.now}")
end
end
EM.run {
ConnectionManager.connection
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment