X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits%2FDBIx-Class.git;a=blobdiff_plain;f=lib%2FDBIx%2FClass%2FStorage%2FDBI%2FReplicated%2FBalancer%2FRandom.pm;h=2b0aef9c2916b0b36f140aaf7ea50a172d673815;hp=1e657b5a77e2108b9e85b03d0e5ea675ab9ba670;hb=ee356d004e088518205ac720b37c31a64c9cd861;hpb=dcdf7b2cd485cc015ddbfd816f6735be075c3386 diff --git a/lib/DBIx/Class/Storage/DBI/Replicated/Balancer/Random.pm b/lib/DBIx/Class/Storage/DBI/Replicated/Balancer/Random.pm index 1e657b5..2b0aef9 100644 --- a/lib/DBIx/Class/Storage/DBI/Replicated/Balancer/Random.pm +++ b/lib/DBIx/Class/Storage/DBI/Replicated/Balancer/Random.pm @@ -2,6 +2,7 @@ package DBIx::Class::Storage::DBI::Replicated::Balancer::Random; use Moose; with 'DBIx::Class::Storage::DBI::Replicated::Balancer'; +use DBIx::Class::Storage::DBI::Replicated::Types 'Weight'; use namespace::clean -except => 'meta'; =head1 NAME @@ -27,6 +28,17 @@ you, patches welcome. This class defines the following attributes. +=head2 master_read_weight + +A number from 0 to 1 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. + +=cut + +has master_read_weight => (is => 'rw', isa => Weight, default => sub { 0 }); + =head1 METHODS This class defines the following methods. @@ -41,11 +53,24 @@ be requested several times in a row. sub next_storage { my $self = shift @_; - my @active_replicants = $self->pool->active_replicants; - my $count_active_replicants = $#active_replicants +1; - my $random_replicant = int(rand($count_active_replicants)); - - return $active_replicants[$random_replicant]; + + my @replicants = $self->pool->active_replicants; + my $master = $self->master; + + my $rnd = $self->random_number(@replicants + $self->master_read_weight); + + return $rnd >= @replicants ? $master : $replicants[int $rnd]; +} + +=head2 random_number + +Returns a random number from 0 to x, not including x. Uses perl's +L by default. + +=cut + +sub random_number { + rand($_[1]) } =head1 AUTHOR