Class: MultiThink::Connection

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

Constant Summary collapse

DEFAULTS =
{retries: 10}

Instance Method Summary collapse

Constructor Details

#initialize(servers, options = {}) ⇒ Connection

Returns a new instance of Connection.



11
12
13
14
15
16
# File 'lib/multithink/connection.rb', line 11

def initialize(servers, options = {})
  @servers = servers
  options = DEFAULTS.merge(options)
  @retries = options.fetch(:retries)
  connect
end

Instance Method Details

#connectObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/multithink/connection.rb', line 18

def connect
  @tried = 0
  while @tried < @retries do
    @servers.each do |server|
      begin
        @conn = r.connect(server)
        return true
      rescue
        sleep 1
      end
    end
  end
  # If we got here we couldn't get a connection. :(
  raise RuntimeError "Error: Reached maximum retries (#{@retries})"
end

#reconnectObject



44
45
46
47
48
49
50
51
52
# File 'lib/multithink/connection.rb', line 44

def reconnect
  begin
    # try fast path first
    @conn.reconnect
  rescue
    # if that fails then try get a new connection
    connect
  end
end

#run(query) ⇒ Object



34
35
36
37
38
39
40
41
42
# File 'lib/multithink/connection.rb', line 34

def run(query)
  begin
    query.run(@conn)
  rescue RuntimeError => e
    if reconnect
      retry
    end
  end
end