Skip to content

Instantly share code, notes, and snippets.

@laser
Last active August 29, 2015 14:00
Show Gist options
  • Save laser/11303869 to your computer and use it in GitHub Desktop.
Save laser/11303869 to your computer and use it in GitHub Desktop.
Using RabbitMQ as Message Broker for RPC (Server)
#!/usr/bin/env ruby
require 'bunny'
require 'json'
require './calculator'
calculator = Calculator.new
# connect to RabbitMQ
conn = Bunny.new
conn.start
# create a channel and exchange that both client and server know about
ch = conn.create_channel
q = ch.queue('calc')
x = ch.default_exchange
q.subscribe(block: true) do |delivery_info, properties, payload|
req_message = JSON.parse payload
# calculate a result
result = calculator.send *(req_message['params'].unshift(req_message['method']))
reply = {
'id' => req_message['id'],
'result' => result,
'jsonrpc' => '2.0'
}
# enqueue our reply in the return queue
x.publish(JSON.generate(reply), {
routing_key: properties.reply_to,
correlation_id: properties.correlation_id
})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment