Class: Roma::Client::ConPool

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/roma/client/con_pool.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(maxlength = 10, expire_time = 60) ⇒ ConPool

Returns a new instance of ConPool.



14
15
16
17
18
19
# File 'lib/roma/client/con_pool.rb', line 14

def initialize(maxlength = 10, expire_time = 60)
  @pool = {}
  @maxlength = maxlength
  @expire_time = expire_time
  @lock = Mutex.new
end

Instance Attribute Details

#expire_timeObject

Returns the value of attribute expire_time.



12
13
14
# File 'lib/roma/client/con_pool.rb', line 12

def expire_time
  @expire_time
end

#maxlengthObject

Returns the value of attribute maxlength.



11
12
13
# File 'lib/roma/client/con_pool.rb', line 11

def maxlength
  @maxlength
end

Instance Method Details

#close_allObject



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

def close_all
  @pool.each_key{|ap| close_at(ap) }
end

#close_at(ap) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/roma/client/con_pool.rb', line 66

def close_at(ap)
  return unless @pool.key?(ap)
  @lock.synchronize {
    while(@pool[ap].length > 0)
      begin
        @pool[ap].shift.close
      rescue =>e
      end
    end
    @pool.delete(ap)
  }
end

#close_same_host(ap) ⇒ Object



59
60
61
62
63
64
# File 'lib/roma/client/con_pool.rb', line 59

def close_same_host(ap)
  host,port = ap.split(/[:_]/)
  @pool.each_key{|eap|
    close_at(eap) if eap.split(/[:_]/)[0] == host
  }
end

#create_connection(ap) ⇒ Object



46
47
48
49
# File 'lib/roma/client/con_pool.rb', line 46

def create_connection(ap)
  addr, port = ap.split(/[:_]/)
  TCPSocket.new(addr, port)
end

#delete_connection(ap) ⇒ Object



51
52
53
# File 'lib/roma/client/con_pool.rb', line 51

def delete_connection(ap)
  @pool.delete(ap)
end

#get_connection(ap) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/roma/client/con_pool.rb', line 21

def get_connection(ap)
  ret,last = @pool[ap].shift if @pool.key?(ap) && @pool[ap].length > 0
  if ret && last < Time.now - @expire_time
    ret.close
    ret = nil
  end
  ret = create_connection(ap) unless ret
  ret
rescue
  nil
end

#return_connection(ap, con) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/roma/client/con_pool.rb', line 33

def return_connection(ap, con)
  if @pool.key?(ap) && @pool[ap].length > 0
    if @pool[ap].length > @maxlength
      con.close
    else
      @pool[ap] << [con, Time.now]
    end
  else
    @pool[ap] = [[con, Time.now]]
  end
rescue
end