Skip to content

Instantly share code, notes, and snippets.

@amscotti
Created August 31, 2014 19:42
Show Gist options
  • Save amscotti/f03f3c9ebe78b28f7223 to your computer and use it in GitHub Desktop.
Save amscotti/f03f3c9ebe78b28f7223 to your computer and use it in GitHub Desktop.
RPC using Redis
require 'redis'
require 'securerandom'
require 'msgpack'
class RedisRpcClient
def initialize(redis_url, list_name)
@client = Redis.connect(url: redis_url)
@list_name = list_name.to_s
end
def method_missing(name, *args)
request = {
'jsonrpc' => '2.0',
'method' => name,
'params' => args,
'id' => SecureRandom.uuid
}
@client.lpush(@list_name, request.to_msgpack)
channel, response = @client.brpop(request['id'], timeout=30)
MessagePack.unpack(response)['result']
end
end
client = RedisRpcClient.new('redis://localhost:6379', :fib)
(1..30).each { |i| puts client.fib(i) }
import redis
import msgpack
class Fibonacci:
def fib(self,n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return self.fib(n-1) + self.fib(n-2)
class RedisRpcServer:
def __init__(self, redis_url, list_name, klass):
self.client = redis.from_url(redis_url)
self.list_name = list_name
self.klass = klass
def start(self):
print("Starting RPC server for " + self.list_name)
while True:
channel, request = self.client.brpop('fib')
request = msgpack.unpackb(request, encoding='utf-8')
print("Working on request: " + request['id'])
result = getattr(self.klass, request['method'])(*request['params'])
reply = {
'jsonrpc': '2.0',
'result': result,
'id': request['id']
}
self.client.rpush(request['id'], msgpack.packb(reply, use_bin_type=True))
self.client.expire(request['id'], 30)
RedisRpcServer('redis://localhost:6379', 'fib', Fibonacci()).start()
require 'redis'
require 'msgpack'
class Fibonacci
def fib(n)
case n
when 0 then 0
when 1 then 1
else
fib(n - 1) + fib(n - 2)
end
end
end
class RedisRpcServer
def initialize(redis_url, list_name, klass)
@client = Redis.connect(url: redis_url)
@list_name = list_name.to_s
@klass = klass
end
def start
puts "Starting RPC server for #{@list_name}"
while true
channel, request = @client.brpop(@list_name)
request = MessagePack.unpack(request)
puts "Working on request: #{request['id']}"
args = request['params'].unshift(request['method'])
result = @klass.send *args
reply = {
'jsonrpc' => '2.0',
'result' => result,
'id' => request['id']
}
@client.rpush(request['id'], MessagePack.pack(reply))
@client.expire(request['id'], 30)
end
end
end
RedisRpcServer.new('redis://localhost:6379', :fib, Fibonacci.new).start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment