Class: Hiredis::ThreadSafeConnection

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

Constant Summary collapse

ACCEPTABLE_FORWARDS =
[:timeout=, :connected?]
STANDBY_POOL_SIZE_DEFAULT =

Spin up 8 threads by default, lazy loading is available, but this can make applications more deterministic

8

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ ThreadSafeConnection

Returns a new instance of ThreadSafeConnection.



6
7
8
# File 'lib/hiredis/thread_safe_connection.rb', line 6

def initialize params={}
  @standby_pool_size = params[:standby_pool_size] || STANDBY_POOL_SIZE_DEFAULT
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



44
45
46
47
48
49
50
51
# File 'lib/hiredis/thread_safe_connection.rb', line 44

def method_missing method, *args, &block
  #Certain calls are ok to forward
  unless ACCEPTABLE_FORWARDS.include? method
    $stderr.puts "WARN: Implementors: please implement #{method.inspect} for Hiredis::ThreadSafeConnection, proxying method for now to Hiredis::Connection"
  end

  self.client.send(method, *args, &block)
end

Instance Method Details

#clientObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/hiredis/thread_safe_connection.rb', line 25

def client
  current_thread_id = Thread.current.object_id
  cached_client = @conns[current_thread_id]

  return cached_client if cached_client

  conn = @standby_pool.pop

  #Ran out of connections in the original pool
  if conn.nil?
    conn = Hiredis::Connection.new
    conn.connect(*@args)
  end

  @conns[current_thread_id] = conn

  return conn
end

#connect(*args) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/hiredis/thread_safe_connection.rb', line 10

def connect *args
  if @conns
    raise "You cannot call connect multiple times on Hiredis::ThreadSafeConnection, please create a new instance if you required this capability"
  end
  @args = args
  @conns = {}

  @standby_pool = []
  @standby_pool_size.times do
    conn = Hiredis::Connection.new
    conn.connect(*@args)
    @standby_pool << conn
  end
end

#readObject



57
58
59
# File 'lib/hiredis/thread_safe_connection.rb', line 57

def read
  self.client.read
end

#write(args) ⇒ Object



53
54
55
# File 'lib/hiredis/thread_safe_connection.rb', line 53

def write args
  self.client.write args
end