]>
git.saurik.com Git - redis.git/blob - client-libraries/ruby_2/rubyredis.rb
1 # RubyRedis is an alternative implementatin of Ruby client library written
2 # by Salvatore Sanfilippo.
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.
12 if (RUBY_VERSION >= '1.9')
16 require 'system_timer'
17 RedisTimer
= SystemTimer
25 "set"=>true, "setnx"=>true, "rpush"=>true, "lpush"=>true, "lset"=>true,
26 "lrem"=>true, "sadd"=>true, "srem"=>true, "sismember"=>true,
27 "echo"=>true, "getset"=>true, "smove"=>true
30 ConvertToBool
= lambda
{|r
| r
== 0 ? false : r
}
33 "exists" => ConvertToBool
,
34 "sismember"=> ConvertToBool
,
35 "sadd"=> ConvertToBool
,
36 "srem"=> ConvertToBool
,
37 "smove"=> ConvertToBool
,
38 "move"=> ConvertToBool
,
39 "setnx"=> ConvertToBool
,
40 "del"=> ConvertToBool
,
41 "renamenx"=> ConvertToBool
,
42 "expire"=> ConvertToBool
,
43 "keys" => lambda
{|r
| r
.split(" ")},
47 k
,v
= kv
.split(":",2).map
{|x
| x
.chomp
}
55 "flush_db" => "flushdb",
56 "flush_all" => "flushall",
57 "last_save" => "lastsave",
60 "randkey" => "randomkey",
61 "list_length" => "llen",
62 "push_tail" => "rpush",
63 "push_head" => "lpush",
67 "list_range" => "lrange",
68 "list_trim" => "ltrim",
69 "list_index" => "lindex",
72 "set_delete" => "srem",
73 "set_count" => "scard",
74 "set_member?" => "sismember",
75 "set_members" => "smembers",
76 "set_intersect" => "sinter",
77 "set_intersect_store" => "sinterstore",
78 "set_inter_store" => "sinterstore",
79 "set_union" => "sunion",
80 "set_union_store" => "sunionstore",
81 "set_diff" => "sdiff",
82 "set_diff_store" => "sdiffstore",
83 "set_move" => "smove",
84 "set_unless_exists" => "setnx",
85 "rename_unless_exists" => "renamenx"
88 def initialize(opts
={})
89 @host = opts
[:host] || '127.0.0.1'
90 @port = opts
[:port] || 6379
92 @timeout = opts
[:timeout] || 0
97 "Redis Client connected to #{@host}:#{@port} against DB #{@db}"
100 def connect_to_server
101 @sock = connect_to(@host,@port,@timeout == 0 ? nil : @timeout)
102 call_command(["select",@db]) if @db !
= 0
105 def connect_to(host
, port
, timeout
=nil)
106 # We support connect() timeout only if system_timer is availabe
107 # or if we are running against Ruby >= 1.9
108 # Timeout reading from the socket instead will be supported anyway.
109 if @timeout !
= 0 and RedisTimer
111 sock
= TCPSocket
.new(host
, port
, 0)
112 rescue Timeout
::Error
114 raise Timeout
::Error, "Timeout connecting to the server"
117 sock
= TCPSocket
.new(host
, port
, 0)
120 # If the timeout is set we set the low level socket options in order
121 # to make sure a blocking read will return after the specified number
122 # of seconds. This hack is from memcached ruby client.
124 secs
= Integer(timeout
)
125 usecs
= Integer((timeout
- secs
) * 1_000_000)
126 optval
= [secs
, usecs
].pack("l_2")
127 sock
.setsockopt Socket
::SOL_SOCKET, Socket
::SO_RCVTIMEO, optval
128 sock
.setsockopt Socket
::SOL_SOCKET, Socket
::SO_SNDTIMEO, optval
133 def method_missing(*argv)
137 def call_command(argv)
138 # this wrapper to raw_call_command handle reconnection on socket
139 # error. We try to reconnect just one time, otherwise let the error
141 connect_to_server
if !
@sock
143 raw_call_command(argv)
144 rescue Errno
::ECONNRESET
147 raw_call_command(argv)
151 def raw_call_command(argv)
153 argv[0] = argv[0].to_s
.downcase
154 argv[0] = Aliases
[argv[0]] if Aliases
[argv[0]]
155 if BulkCommands
[argv[0]] and argv.length
> 1
157 argv[-1] = bulk
.length
159 @sock.write(argv.join(" ")+
"\r\n")
160 @sock.write(bulk+
"\r\n") if bulk
162 # Post process the reply if needed
163 processor
= ReplyProcessor
[argv[0]]
164 processor
? processor
.call(read_reply
) : read_reply
168 raise "SELECT not allowed, use the :db option when creating the object"
179 def sort(key
, opts
={})
182 cmd
<< "BY #{opts[:by]}" if opts
[:by]
183 cmd
<< "GET #{[opts[:get]].flatten * ' GET '}" if opts
[:get]
184 cmd
<< "#{opts[:order]}" if opts
[:order]
185 cmd
<< "LIMIT #{opts[:limit].join(' ')}" if opts
[:limit]
189 def incr(key
,increment
=nil)
190 call_command(increment
? ["incrby",key
,increment
] : ["incr",key
])
193 def decr(key
,decrement
=nil)
194 call_command(decrement
? ["decrby",key
,decrement
] : ["decr",key
])
198 # We read the first byte using read() mainly because gets() is
199 # immune to raw socket timeouts.
201 rtype
= @sock.read(1)
203 # We want to make sure it reconnects on the next command after the
204 # timeout. Otherwise the server may reply in the meantime leaving
205 # the protocol in a desync status.
207 raise Errno
::EAGAIN, "Timeout reading from the socket"
210 raise Errno
::ECONNRESET,"Connection lost" if !rtype
221 return nil if bulklen == -1
222 data = @sock.read(bulklen)
227 return nil if bulklen == -1
234 raise "Protocol error
, got
'#{rtype}' as initial reply byte
"