X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=blobdiff_plain;f=lib%2FDBIx%2FClass%2FStorage%2FDBI%2FReplicated%2FBalancer%2FRandom.pm;h=1fc7b94e7374b107f9ad2c481b9e536a89240759;hb=7cfda9a6b80a051ffd5b180c4d34b66eae0de38d;hp=66f08279195d9a1ae62aeb426954f59b608017ad;hpb=cb6ec758e3c4607ec8e30dd943a500a1d70d8940;p=dbsrgits%2FDBIx-Class.git diff --git a/lib/DBIx/Class/Storage/DBI/Replicated/Balancer/Random.pm b/lib/DBIx/Class/Storage/DBI/Replicated/Balancer/Random.pm index 66f0827..1fc7b94 100644 --- a/lib/DBIx/Class/Storage/DBI/Replicated/Balancer/Random.pm +++ b/lib/DBIx/Class/Storage/DBI/Replicated/Balancer/Random.pm @@ -1,18 +1,19 @@ package DBIx::Class::Storage::DBI::Replicated::Balancer::Random; -use List::Util qw(shuffle); use Moose; -extends 'DBIx::Class::Storage::DBI::Replicated::Balancer'; +with 'DBIx::Class::Storage::DBI::Replicated::Balancer'; +use DBIx::Class::Storage::DBI::Replicated::Types 'Weight'; +use namespace::clean -except => 'meta'; =head1 NAME -DBIx::Class::Storage::DBI::Replicated::Balancer; A Software Load Balancer +DBIx::Class::Storage::DBI::Replicated::Balancer::Random - A 'random' Balancer =head1 SYNOPSIS This class is used internally by L. You shouldn't need to create instances of this class. - + =head1 DESCRIPTION Given a pool (L) of replicated @@ -27,6 +28,23 @@ you, patches welcome. This class defines the following attributes. +=head2 master_read_weight + +A number greater than 0 that specifies what weight to give the master when +choosing which backend to execute a read query on. A value of 0, which is the +default, does no reads from master, while a value of 1 gives it the same +priority as any single replicant. + +For example: if you have 2 replicants, and a L of C<0.5>, +the chance of reading from master will be C<20%>. + +You can set it to a value higher than 1, making master have higher weight than +any single replicant, if for example you have a very powerful master. + +=cut + +has master_read_weight => (is => 'rw', isa => Weight, default => sub { 0 }); + =head1 METHODS This class defines the following methods. @@ -40,11 +58,25 @@ be requested several times in a row. =cut sub next_storage { - my $self = shift @_; - return (shuffle($self->pool->active_replicants))[0] - if $self->pool->active_replicants; + my $self = shift @_; + + my @replicants = $self->pool->active_replicants; + + if (not @replicants) { + # will fall back to master anyway + return; + } + + my $master = $self->master; + + my $rnd = $self->_random_number(@replicants + $self->master_read_weight); + + return $rnd >= @replicants ? $master : $replicants[int $rnd]; } +sub _random_number { + rand($_[1]) +} =head1 AUTHOR @@ -56,4 +88,6 @@ You may distribute this code under the same terms as Perl itself. =cut -1; \ No newline at end of file +__PACKAGE__->meta->make_immutable; + +1;