Last active
August 29, 2015 14:00
-
-
Save laser/11303750 to your computer and use it in GitHub Desktop.
Using Redis 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 '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