]>
git.saurik.com Git - redis.git/blob - client-libraries/ruby_2/rubyredis.rb
85989d35f458c8eb80830abd1e09beeeaf11f079
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.
11 if (RUBY_VERSION >= '1.9')
15 require 'system_timer'
16 RedisTimer
= SystemTimer
24 "set"=>true, "setnx"=>true, "rpush"=>true, "lpush"=>true, "lset"=>true,
25 "lrem"=>true, "sadd"=>true, "srem"=>true, "sismember"=>true,
26 "echo"=>true, "getset"=>true, "smove"=>true
29 ConvertToBool
= lambda
{|r
| r
== 0 ? false : r
}
32 "exists" => ConvertToBool
,
33 "sismember"=> ConvertToBool
,
34 "sadd"=> ConvertToBool
,
35 "srem"=> ConvertToBool
,
36 "smove"=> ConvertToBool
,
37 "move"=> ConvertToBool
,
38 "setnx"=> ConvertToBool
,
39 "del"=> ConvertToBool
,
40 "renamenx"=> ConvertToBool
,
41 "expire"=> ConvertToBool
,
42 "keys" => lambda
{|r
| r
.split(" ")},
46 k
,v
= kv
.split(":",2).map
{|x
| x
.chomp
}
54 "flush_db" => "flushdb",
55 "flush_all" => "flushall",
56 "last_save" => "lastsave",
59 "randkey" => "randomkey",
60 "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_inter_store" => "sinterstore",
78 "set_union" => "sunion",
79 "set_union_store" => "sunionstore",
80 "set_diff" => "sdiff",
81 "set_diff_store" => "sdiffstore",
82 "set_move" => "smove",
83 "set_unless_exists" => "setnx"
86 def initialize(opts
={})
87 @host = opts
[:host] || '127.0.0.1'
88 @port = opts
[:port] || 6379
90 @timeout = opts
[:timeout] || 0
95 "Redis Client connected to #{@host}:#{@port} against DB #{@db}"
99 @sock = connect_to(@host,@port,@timeout == 0 ? nil : @timeout)
100 call_command(["select",@db]) if @db !
= 0
103 def connect_to(host
, port
, timeout
=nil)
104 # We support connect() timeout only if system_timer is availabe
105 # or if we are running against Ruby >= 1.9
106 # Timeout reading from the socket instead will be supported anyway.
107 if @timeout !
= 0 and RedisTimer
109 sock
= TCPSocket
.new(host
, port
, 0)
110 rescue Timeout
::Error
111 raise Timeout
::Error, "Timeout connecting to the server"
114 sock
= TCPSocket
.new(host
, port
, 0)
117 # If the timeout is set we set the low level socket options in order
118 # to make sure a blocking read will return after the specified number
119 # of seconds. This hack is from memcached ruby client.
121 secs
= Integer(timeout
)
122 usecs
= Integer((timeout
- secs
) * 1_000_000)
123 optval
= [secs
, usecs
].pack("l_2")
124 sock
.setsockopt Socket
::SOL_SOCKET, Socket
::SO_RCVTIMEO, optval
125 sock
.setsockopt Socket
::SOL_SOCKET, Socket
::SO_SNDTIMEO, optval
130 def method_missing(*argv)
134 def call_command(argv)
135 # this wrapper to raw_call_command handle reconnection on socket
136 # error. We try to reconnect just one time, otherwise let the error
138 connect_to_server
if !
@sock
140 raw_call_command(argv)
141 rescue Errno
::ECONNRESET
144 raw_call_command(argv)
148 def raw_call_command(argv)
150 argv[0] = argv[0].to_s
.downcase
151 argv[0] = Aliases
[argv[0]] if Aliases
[argv[0]]
152 if BulkCommands
[argv[0]]
154 argv[-1] = bulk
.length
156 @sock.write(argv.join(" ")+
"\r\n")
157 @sock.write(bulk+
"\r\n") if bulk
159 # Post process the reply if needed
160 processor
= ReplyProcessor
[argv[0]]
161 processor
? processor
.call(read_reply
) : read_reply
165 raise "SELECT not allowed, use the :db option when creating the object"
176 def sort(key
, opts
={})
179 cmd
<< "BY #{opts[:by]}" if opts
[:by]
180 cmd
<< "GET #{[opts[:get]].flatten * ' GET '}" if opts
[:get]
181 cmd
<< "#{opts[:order]}" if opts
[:order]
182 cmd
<< "LIMIT #{opts[:limit].join(' ')}" if opts
[:limit]
186 def incr(key
,increment
=nil)
187 call_command(increment
? ["incrby",key
,increment
] : ["incr",key
])
190 def decr(key
,decrement
=nil)
191 call_command(decrement
? ["decrby",key
,decrement
] : ["decr",key
])
195 # We read the first byte using read() mainly because gets() is
196 # immune to raw socket timeouts.
198 rtype
= @sock.read(1)
200 # We want to make sure it reconnects on the next command after the
201 # timeout. Otherwise the server may reply in the meantime leaving
202 # the protocol in a desync status.
204 raise Errno
::EAGAIN, "Timeout reading from the socket"
207 raise Errno
::ECONNRESET,"Connection lost" if !rtype
218 return nil if bulklen == -1
219 data = @sock.read(bulklen)
224 return nil if bulklen == -1
231 raise "Protocol error
, got
'#{rtype}' as initial reply bye
"