Class: Fastbeans::Client

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

Constant Summary collapse

CALL_CACHE_SIZE =
100
MAX_RETRIES =
3

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host = "127.0.0.1", port = 12345, cache_size = nil, pool_opts = {}) ⇒ Client

Returns a new instance of Client.



15
16
17
18
19
20
# File 'lib/fastbeans/client.rb', line 15

def initialize(host="127.0.0.1", port=12345, cache_size=nil, pool_opts={})
  @host, @port = host, port
  @cache_size ||= CALL_CACHE_SIZE
  @call_cache = Rufus::Lru::SynchronizedHash.new(@cache_size)
  @pool_opts =  {:size => 5, :timeout => 5}.update(pool_opts)
end

Instance Attribute Details

#call_cacheObject (readonly)

Returns the value of attribute call_cache.



13
14
15
# File 'lib/fastbeans/client.rb', line 13

def call_cache
  @call_cache
end

Instance Method Details

#cached_call(*data) ⇒ Object



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

def cached_call(*data)
  @call_cache[data] ||= call(*data)
end

#call(*data) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/fastbeans/client.rb', line 32

def call(*data)
  Fastbeans.benchmark("Calling: #{data.inspect}") do
    retries = 0
    begin
      call_without_retries(*data)
    rescue Fastbeans::RemoteConnectionFailed => e
      Fastbeans.debug(e)
      if retries < MAX_RETRIES
        Fastbeans.debug("Retrying (#{retries} out of #{MAX_RETRIES} retries)")
        retries += 1
        begin
          reconnect!
        rescue => e
          raise RemoteConnectionDead, e.message
        end
        retry
      else
        raise RemoteConnectionDead, "#{e.message} (#{retries} retries)"
      end
    end
  end
end

#call_without_retries(*data) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/fastbeans/client.rb', line 59

def call_without_retries(*data)
  raw_resp = pool.with do |conn|
    payload = MessagePack.pack(data).force_encoding("BINARY")
    conn.write([payload.bytesize].pack("N"))
    conn.write(payload)
    MessagePack.load(conn.socket)
  end
  resp = Response.new(data, raw_resp)
  resp.payload
rescue IOError, Errno::EPIPE, MessagePack::MalformedFormatError => e
  ne = RemoteConnectionFailed.new(e.message)
  ne.orig_exc = e
  raise ne
end

#clear_call_cache!Object



28
29
30
# File 'lib/fastbeans/client.rb', line 28

def clear_call_cache!
  @call_cache.clear
end

#poolObject



22
23
24
25
26
# File 'lib/fastbeans/client.rb', line 22

def pool
  @pool ||= ConnectionPool.new(@pool_opts) do
    Fastbeans::Connection.new(@host, @port)
  end
end