Class: DistRedis

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

Overview

require ‘redis’ require ‘hash_ring’

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/redis_ext/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/redis_ext/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/redis_ext/dist_redis.rb', line 4

def ring
  @ring
end

Instance Method Details

#add_server(server) ⇒ Object



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

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

#bgsaveObject



49
50
51
# File 'lib/redis_ext/dist_redis.rb', line 49

def bgsave
  on_each_node :bgsave
end

#delete_cloud!Object



67
68
69
70
71
72
73
# File 'lib/redis_ext/dist_redis.rb', line 67

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



57
58
59
# File 'lib/redis_ext/dist_redis.rb', line 57

def flush_all
  on_each_node :flush_all
end

#flush_dbObject Also known as: flushdb



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

def flush_db
  on_each_node :flush_db
end

#keys(glob) ⇒ Object



39
40
41
42
43
# File 'lib/redis_ext/dist_redis.rb', line 39

def keys(glob)
  @ring.nodes.map do |red|
    red.keys(glob)
  end
end

#node_for_key(key) ⇒ Object



21
22
23
24
# File 'lib/redis_ext/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



75
76
77
78
79
# File 'lib/redis_ext/dist_redis.rb', line 75

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

#quitObject



53
54
55
# File 'lib/redis_ext/dist_redis.rb', line 53

def quit
  on_each_node :quit
end

#saveObject



45
46
47
# File 'lib/redis_ext/dist_redis.rb', line 45

def save
  on_each_node :save
end