| 1 | package Beanstalk::Pool; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use base qw(Class::Accessor::Fast); | ||
| 7 | |||
| 8 | our $VERSION = "0.00_01"; | ||
| 9 | |||
| 10 | BEGIN { | ||
| 11 | __PACKAGE__->mk_accessors( | ||
| 12 | qw(servers clients default_tube mode _current retries _watching _use) | ||
| 13 | ); | ||
| 14 | } | ||
| 15 | |||
| 16 | sub _connect { | ||
| 17 | my $self = shift; | ||
| 18 | my $client = shift; | ||
| 19 | |||
| 20 | $client->connect; | ||
| 21 | if (defined (my $use = $self->_use)) { | ||
| 22 | $client->use($use); | ||
| 23 | } | ||
| 24 | if (my $watching = $self->_watching) { | ||
| 25 | $client->watch_only(keys %watching); | ||
| 26 | } | ||
| 27 | } | ||
| 28 | |||
| 29 | sub next_client { | ||
| 30 | my $self = shift; | ||
| 31 | my $disconnect = shift; | ||
| 32 | |||
| 33 | my $current = $self->_current; | ||
| 34 | my $clients = $self->clients; | ||
| 35 | |||
| 36 | my $mode = $self->mode; | ||
| 37 | |||
| 38 | if ($mode eq 'random') { | ||
| 39 | $current = int rand(scalar @$clients); | ||
| 40 | } | ||
| 41 | else { # if ($mode eq 'round-robin') { | ||
| 42 | ++$current; | ||
| 43 | $current = 0 if $current >= @$clients; | ||
| 44 | } | ||
| 45 | |||
| 46 | $self->_current($current); | ||
| 47 | my $client = $clients->[$current]; | ||
| 48 | _connect($self, $client) unless $client->socket; | ||
| 49 | return $client; | ||
| 50 | } | ||
| 51 | |||
| 52 | |||
| 53 | sub new { | ||
| 54 | my $proto = shift; | ||
| 55 | my $opt = shift || {}; | ||
| 56 | my $self = $proto->SUPER::new({ | ||
| 57 | mode => 'round-robin', | ||
| 58 | retries => 3, | ||
| 59 | %$opt, | ||
| 60 | }); | ||
| 61 | } | ||
| 62 | |||
| 63 | sub connect { | ||
| 64 | my $self = shift; | ||
| 65 | |||
| 66 | my $default_tube = $self->default_tube; | ||
| 67 | |||
| 68 | my @clients; | ||
| 69 | |||
| 70 | foreach my $server (@{ $self->servers }) { | ||
| 71 | my $client = Beanstalk::Client->new({ | ||
| 72 | server => $server, | ||
| 73 | default_tube => $default_tube, | ||
| 74 | }); | ||
| 75 | _connect($self, $client); | ||
| 76 | } | ||
| 77 | $self->clients(\@clients); | ||
| 78 | 1; | ||
| 79 | } | ||
| 80 | |||
| 81 | |||
| 82 | |||
| 83 | 1; | ||
| 84 | |||
| 85 | __END__ |