1 package DBIx::Class::Storage::DBI::Replicated::Balancer::Random;
4 use DBIx::Class::Storage::DBI::Replicated::Types qw(PositiveNumber);
5 with 'DBIx::Class::Storage::DBI::Replicated::Balancer';
9 DBIx::Class::Storage::DBI::Replicated::Balancer::Random - A 'random' Balancer
13 This class is used internally by L<DBIx::Class::Storage::DBI::Replicated>. You
14 shouldn't need to create instances of this class.
18 Given a pool (L<DBIx::Class::Storage::DBI::Replicated::Pool>) of replicated
19 database's (L<DBIx::Class::Storage::DBI::Replicated::Replicant>), defines a
20 method by which query load can be spread out across each replicant in the pool.
24 This class defines the following attributes.
26 =head2 master_read_weight
28 A number greater than 0 that specifies what weight to give the master when
29 choosing which backend to execute a read query on. A value of 0, which is the
30 default, does no reads from master, while a value of 1 gives it the same
31 priority as any single replicant.
33 For example: if you have 2 replicants, and a L</master_read_weight> of C<0.5>,
34 the chance of reading from master will be C<20%>.
36 You can set it to a value higher than 1, making master have higher weight than
37 any single replicant, if for example you have a very powerful master.
41 has master_read_weight => (
43 isa => PositiveNumber(err => sub {"weight must be a positive number, not $_[0]"}),
49 This class defines the following methods.
53 Returns an active replicant at random. Please note that due to the nature of
54 the word 'random' this means it's possible for a particular active replicant to
55 be requested several times in a row.
61 my @replicants = $self->pool->active_replicants;
63 if (not @replicants) {
64 # will fall back to master anyway
68 my $master = $self->master;
69 my $rnd = $self->_random_number(@replicants + $self->master_read_weight);
71 return $rnd >= @replicants ? $master : $replicants[int $rnd];
80 John Napiorkowski <jjnapiork@cpan.org>
84 You may distribute this code under the same terms as Perl itself.