-
-
Save hassox/307177 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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