Skip to content

Commit

Permalink
channel pools
Browse files Browse the repository at this point in the history
  • Loading branch information
danielsdeleo committed Jul 11, 2009
1 parent 6726194 commit 2b495d6
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/qusion.rb
Expand Up @@ -5,6 +5,10 @@

require QUSION_ROOT + "qusion/em"
require QUSION_ROOT + "qusion/amqp"
require QUSION_ROOT + "qusion/channel_pool"

module Qusion
def self.channel
ChannelPool.instance.channel
end
end
44 changes: 44 additions & 0 deletions lib/qusion/channel_pool.rb
@@ -0,0 +1,44 @@
# encoding: UTF-8
require "singleton"

module Qusion
class ChannelPool
include Singleton

class << self
attr_writer :pool_size

def pool_size
@pool_size || 5
end

def reset
@pool_size = nil
instance.reset
end

end

def channel
channel = @pool.shift
@pool << channel
channel
end

def pool
@pool ||= initialize_pool
end

def initialize_pool
@pool = []
self.class.pool_size.times do
@pool << MQ.new
end
end

def reset
@pool = nil
end

end
end
48 changes: 48 additions & 0 deletions spec/unit/channel_pool_spec.rb
@@ -0,0 +1,48 @@
# encoding: UTF-8
require File.dirname(__FILE__) + "/../spec_helper"

describe ChannelPool do
MQ = Object.new

before(:each) do
ChannelPool.reset
end

it "should be singleton" do
lambda { ChannelPool.new }.should raise_error
end

it "should adjust the pool size" do
ChannelPool.pool_size = 5
ChannelPool.pool_size.should == 5
end

it "should create a pool of AMQP channels" do
ChannelPool.pool_size = 3
MQ.should_receive(:new).exactly(3).times
ChannelPool.instance.pool
end

it "should default to a pool size of 5" do
MQ.should_receive(:new).exactly(5).times
ChannelPool.instance.pool
end

it "should return a channel in a round-robin" do
ChannelPool.instance.instance_variable_set(:@pool, [1,2,3,4,5])
[1,2,3,4,5,1,2,3,4,5].each do |i|
ChannelPool.instance.channel.should == i
end

end

end

describe Qusion do
it "should provide a convenience method to get a channel from the pool" do
channel_pool = mock("channel pool")
ChannelPool.should_receive(:instance).and_return(channel_pool)
channel_pool.should_receive(:channel)
Qusion.channel
end
end

0 comments on commit 2b495d6

Please sign in to comment.