Class: DistRedis

Inherits:
Object
  • Object
show all
Defined in:
lib/dist_redis.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ DistRedis

Returns a new instance of DistRedis.

Raises:

  • (Error)


5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/dist_redis.rb', line 5

def initialize(opts={})
  hosts = []

  db = opts[:db] || nil
  timeout = opts[:timeout] || nil

  raise Error, "No hosts given" unless opts[:hosts]

  opts[:hosts].each do |h|
    host, port = h.split(':')
    hosts << Redis.new(:host => host, :port => port, :db => db, :timeout => timeout)
  end

  @ring = HashRing.new hosts
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &blk) ⇒ Object



31
32
33
34
35
36
37
# File 'lib/dist_redis.rb', line 31

def method_missing(sym, *args, &blk)
  if redis = node_for_key(args.first.to_s)
    redis.send sym, *args, &blk
  else
    super
  end
end

Instance Attribute Details

#ringObject (readonly)

Returns the value of attribute ring.



4
5
6
# File 'lib/dist_redis.rb', line 4

def ring
  @ring
end

Instance Method Details

#add_server(server) ⇒ Object



26
27
28
29
# File 'lib/dist_redis.rb', line 26

def add_server(server)
  server, port = server.split(':')
  @ring.add_node Redis.new(:host => server, :port => port)
end

#bgsaveObject



59
60
61
# File 'lib/dist_redis.rb', line 59

def bgsave
  on_each_node :bgsave
end

#delete_cloud!Object



77
78
79
80
81
82
83
# File 'lib/dist_redis.rb', line 77

def delete_cloud!
  @ring.nodes.each do |red|
    red.keys("*").each do |key|
      red.delete key
    end
  end
end

#flush_allObject Also known as: flushall



67
68
69
# File 'lib/dist_redis.rb', line 67

def flush_all
  on_each_node :flush_all
end

#flush_dbObject Also known as: flushdb



72
73
74
# File 'lib/dist_redis.rb', line 72

def flush_db
  on_each_node :flush_db
end

#keys(glob) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/dist_redis.rb', line 47

def keys(glob)
  keyz = []
  @ring.nodes.each do |red|
    keyz.concat red.keys(glob)
  end
  keyz
end

#node_for_key(key) ⇒ Object



21
22
23
24
# File 'lib/dist_redis.rb', line 21

def node_for_key(key)
  key = $1 if key =~ /\{(.*)?\}/
  @ring.get_node(key)
end

#on_each_node(command, *args) ⇒ Object



85
86
87
88
89
# File 'lib/dist_redis.rb', line 85

def on_each_node(command, *args)
  @ring.nodes.each do |red|
    red.send(command, *args)
  end
end

#quitObject



63
64
65
# File 'lib/dist_redis.rb', line 63

def quit
  on_each_node :quit
end

#saveObject



55
56
57
# File 'lib/dist_redis.rb', line 55

def save
  on_each_node :save
end

#type(key) ⇒ Object

Ruby defines a now deprecated type method so we need to override it here since it will never hit method_missing



41
42
43
44
45
# File 'lib/dist_redis.rb', line 41

def type(key)
  if redis = node_for_key(key)
    redis.send :type, key
  end
end