]>
Commit | Line | Data |
---|---|---|
4a327b4a | 1 | # RubyRedis is an alternative implementatin of Ruby client library written |
2 | # by Salvatore Sanfilippo. | |
3 | # | |
4 | # The aim of this library is to create an alternative client library that is | |
5 | # much simpler and does not implement every command explicitly but uses | |
6 | # method_missing instead. | |
7 | ||
8 | require 'socket' | |
9 | ||
10 | class RedisClient | |
11 | BulkCommands = { | |
12 | "set"=>true, "setnx"=>true, "rpush"=>true, "lpush"=>true, "lset"=>true, | |
13 | "lrem"=>true, "sadd"=>true, "srem"=>true, "sismember"=>true, | |
14 | "echo"=>true, "getset"=>true, "smove"=>true | |
15 | } | |
16 | ||
17 | def initialize(opts={}) | |
18 | opts = {:host => 'localhost', :port => '6379', :db => 0}.merge(opts) | |
19 | @host = opts[:host] | |
20 | @port = opts[:port] | |
21 | @db = opts[:db] | |
22 | @sock = connect_to_server | |
4e1684df | 23 | call_command(["select",@db]) if @db != 0 |
4a327b4a | 24 | end |
25 | ||
26 | def to_s | |
27 | "Redis Client connected to #{@host}:#{@port} against DB #{@db}" | |
28 | end | |
29 | ||
30 | def connect_to_server | |
31 | TCPSocket.new(@host, @port, 0) | |
32 | end | |
33 | ||
34 | def method_missing(*argv) | |
35 | call_command(argv) | |
36 | end | |
37 | ||
38 | def call_command(argv) | |
39 | bulk = nil | |
40 | argv[0] = argv[0].to_s.downcase | |
41 | if BulkCommands[argv[0]] | |
42 | bulk = argv[-1] | |
43 | argv[-1] = bulk.length | |
44 | end | |
45 | @sock.write(argv.join(" ")+"\r\n") | |
46 | @sock.write(bulk+"\r\n") if bulk | |
47 | read_reply | |
48 | end | |
49 | ||
4e1684df | 50 | def select(*args) |
51 | raise "SELECT not allowed, use the :db option when creating the object" | |
52 | end | |
53 | ||
4a327b4a | 54 | def read_reply |
55 | line = @sock.gets | |
56 | case line[0..0] | |
57 | when "-" | |
58 | raise line.strip | |
59 | when "+" | |
60 | line[1..-1].strip | |
61 | when ":" | |
62 | line[1..-1].to_i | |
63 | when "$" | |
64 | bulklen = line[1..-1].to_i | |
65 | return nil if bulklen == -1 | |
66 | data = @sock.read(bulklen) | |
67 | @sock.read(2) # CRLF | |
68 | data | |
69 | when "*" | |
70 | objects = line[1..-1].to_i | |
71 | return nil if bulklen == -1 | |
72 | res = [] | |
73 | objects.times { | |
74 | res << read_reply | |
75 | } | |
76 | res | |
77 | end | |
78 | end | |
79 | end |