Skip to content

Instantly share code, notes, and snippets.

@laser
Last active August 29, 2015 14:00
Show Gist options
  • Save laser/11304574 to your computer and use it in GitHub Desktop.
Save laser/11304574 to your computer and use it in GitHub Desktop.
Fancy Redis Client (using method_missing)
#!/usr/bin/env ruby
require 'redis'
require 'securerandom'
require 'json'
class RedisRpcClient
def initialize(redis_url, list_name)
@redis_client = Redis.connect(url: redis_url)
@list_name = list_name
end
def method_missing(name, *args)
request = {
'id' => SecureRandom.hex,
'jsonrpc' => '2.0',
'method' => name,
'params' => args
}
# insert our request at the head of the list
@redis_client.lpush(@list_name, JSON.generate(request))
# pop last element off our list in a blocking fashion
channel, response = @redis_client.brpop(request['id'], timeout=30)
parsed = JSON.parse(response)
parsed['result']
end
end
# create the client and connect to Redis
client = RedisRpcClient.new('redis://localhost:6379')
# remote a call to 'add'
sum = client.add(1, 5.1)
# print it out to the console
puts "1+5.1=%.1f" % sum # 1+5.1=6.1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment