box-o-sand/oldstuff/sylvilagus/jruby/lib/sylvilagus/ch04/alert_producer.rb
2015-06-22 13:15:42 -05:00

50 lines
1.5 KiB
Ruby

require 'sylvilagus/init'
require 'sylvilagus/ch04'
require 'optparse'
require 'json'
require 'rabbitmq-client.jar'
class Sylvilagus::Ch04::AlertProducer
def main
options = {}
OptionParser.new do |opts|
opts.on('-rROUTING_KEY', '--routing-key=ROUTING_KEY',
'Routing key for message (e.g. myalert.im)') do |r|
options[:routing_key] = r
end
opts.on('-mMESSAGE', '--message=MESSAGE',
'Message text for alert.') do |m|
options[:message] = m
end
end.parse!
unless options[:message] && options[:routing_key]
STDERR.puts 'Need both message and routing_key!'
exit 1
end
factory = Java::ComRabbitmqClient::ConnectionFactory.new
factory.uri = ENV.fetch('SYLVILAGUS_ALERT_AMQP_URI')
@conn = factory.new_connection
channel = @conn.create_channel
channel.exchange_declare('alerts', 'topic', true, false, false, nil)
props = Java::ComRabbitmqClient::AMQP::BasicProperties.new
props.content_type = 'application/json'
json_msg = JSON.dump({'message' => options[:message]})
channel.basic_publish('alerts', options[:routing_key],
true, true, props, json_msg.to_java_bytes)
puts "Sent message #{json_msg.inspect} tagged " <<
"with routing key #{options[:routing_key].inspect} to " <<
'exchange "alerts" on vhost "/".'
ensure
@conn.close if @conn
end
end
if $0 == __FILE__
Sylvilagus::Ch04::AlertProducer.new.main
end