Skip to content

Instantly share code, notes, and snippets.

@laser
Last active August 29, 2015 14:00
Show Gist options
  • Save laser/11303750 to your computer and use it in GitHub Desktop.
Save laser/11303750 to your computer and use it in GitHub Desktop.
Using Redis as Message Broker for RPC (Server)
#!/usr/bin/env ruby
require 'redis'
require 'json'
require './calculator'
calculator = Calculator.new
# connect to Redis
redis_client = Redis.connect(url: 'redis://localhost:6379')
while true
# pop last element off our list in a blocking fashion
channel, request = redis_client.brpop('calc')
request = JSON.parse request
# call a method on the calculator instance, passing along params
args = request['params'].unshift(request['method'])
result = calculator.send *args
reply = {
'id' => request['id'],
'result' => result,
'jsonrpc' => '2.0'
}
# 'respond' by inserting our reply at the tail of a 'reply'-list
redis_client.rpush(request['id'], JSON.generate(reply))
# set an expire time for our list to make sure we don't leak
redis_client.expire(req_message['id'], 30)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment