Last active
August 29, 2015 14:00
-
-
Save laser/11303869 to your computer and use it in GitHub Desktop.
Using RabbitMQ as Message Broker for RPC (Server)
This file contains hidden or 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
#!/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