]> git.saurik.com Git - redis.git/blob - client-libraries/ruby/lib/dist_redis.rb
ignore gcc warning about write() return code not checked. It is esplicitily this...
[redis.git] / client-libraries / ruby / lib / dist_redis.rb
1 require 'redis'
2 require 'hash_ring'
3 class DistRedis
4 attr_reader :ring
5 def initialize(*servers)
6 srvs = []
7 servers.each do |s|
8 server, port = s.split(':')
9 srvs << Redis.new(:host => server, :port => port)
10 end
11 @ring = HashRing.new srvs
12 end
13
14 def node_for_key(key)
15 if key =~ /\{(.*)?\}/
16 key = $1
17 end
18 @ring.get_node(key)
19 end
20
21 def add_server(server)
22 server, port = server.split(':')
23 @ring.add_node Redis.new(:host => server, :port => port)
24 end
25
26 def method_missing(sym, *args, &blk)
27 if redis = node_for_key(args.first.to_s)
28 redis.send sym, *args, &blk
29 else
30 super
31 end
32 end
33
34 def keys(glob)
35 keyz = []
36 @ring.nodes.each do |red|
37 keyz.concat red.keys(glob)
38 end
39 keyz
40 end
41
42 def save
43 @ring.nodes.each do |red|
44 red.save
45 end
46 end
47
48 def bgsave
49 @ring.nodes.each do |red|
50 red.bgsave
51 end
52 end
53
54 def quit
55 @ring.nodes.each do |red|
56 red.quit
57 end
58 end
59
60 def delete_cloud!
61 @ring.nodes.each do |red|
62 red.keys("*").each do |key|
63 red.delete key
64 end
65 end
66 end
67
68 end
69
70
71 if __FILE__ == $0
72
73 r = DistRedis.new 'localhost:6379', 'localhost:6380', 'localhost:6381', 'localhost:6382'
74 r['urmom'] = 'urmom'
75 r['urdad'] = 'urdad'
76 r['urmom1'] = 'urmom1'
77 r['urdad1'] = 'urdad1'
78 r['urmom2'] = 'urmom2'
79 r['urdad2'] = 'urdad2'
80 r['urmom3'] = 'urmom3'
81 r['urdad3'] = 'urdad3'
82 p r['urmom']
83 p r['urdad']
84 p r['urmom1']
85 p r['urdad1']
86 p r['urmom2']
87 p r['urdad2']
88 p r['urmom3']
89 p r['urdad3']
90
91 r.push_tail 'listor', 'foo1'
92 r.push_tail 'listor', 'foo2'
93 r.push_tail 'listor', 'foo3'
94 r.push_tail 'listor', 'foo4'
95 r.push_tail 'listor', 'foo5'
96
97 p r.pop_tail('listor')
98 p r.pop_tail('listor')
99 p r.pop_tail('listor')
100 p r.pop_tail('listor')
101 p r.pop_tail('listor')
102
103 puts "key distribution:"
104
105 r.ring.nodes.each do |red|
106 p [red.port, red.keys("*")]
107 end
108 r.delete_cloud!
109 p r.keys('*')
110
111 end