Class: RedisMasterSlave::Client

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

Overview

Wrapper around a pair of Redis connections, one master and one slave.

Read requests are directed to the slave, others are sent to the master.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Client

Create a new client.

master and slave may be URL strings, Redis client option hashes, or Redis clients.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/redis_master_slave/client.rb', line 18

def initialize(*args)
  case args.size
  when 1
    config = args.first

    master_config = config['master'] || config[:master]
    slave_configs = config['slaves'] || config[:slaves]
  when 2
    master_config, slave_configs = *args
  else
    raise ArgumentError, "wrong number of arguments (#{args.size} for 1..2)"
  end

  @master = make_client(master_config) or
    extend ReadOnly
  @slaves = slave_configs.map{|config| make_client(config)}
  @index  = 0
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object

Send everything else to master.



121
122
123
124
125
126
127
128
# File 'lib/redis_master_slave/client.rb', line 121

def method_missing(name, *args, &block) # :nodoc:
  if writable_master.respond_to?(name)
    Client.send(:send_to_master, name)
    send(name, *args, &block)
  else
    super
  end
end

Instance Attribute Details

#indexObject

Index of the slave to use for the next read.



50
51
52
# File 'lib/redis_master_slave/client.rb', line 50

def index
  @index
end

#masterObject Also known as: writable_master

The master client.



40
41
42
# File 'lib/redis_master_slave/client.rb', line 40

def master
  @master
end

#slavesObject

The slave client.



45
46
47
# File 'lib/redis_master_slave/client.rb', line 45

def slaves
  @slaves
end

Instance Method Details

#next_slaveObject

Return the next read slave to use.

Each call returns the following slave in sequence.



57
58
59
60
61
# File 'lib/redis_master_slave/client.rb', line 57

def next_slave
  slave = slaves[index]
  @index = (index + 1) % slaves.size
  slave
end