1 package DBIx::Class::Storage::DBI::Replicated::Balancer::Random;
4 with 'DBIx::Class::Storage::DBI::Replicated::Balancer';
5 use DBIx::Class::_Types qw(PositiveNumber);
11 DBIx::Class::Storage::DBI::Replicated::Balancer::Random - A 'random' Balancer
15 This class is used internally by L<DBIx::Class::Storage::DBI::Replicated>. You
16 shouldn't need to create instances of this class.
20 Given a pool (L<DBIx::Class::Storage::DBI::Replicated::Pool>) of replicated
21 database's (L<DBIx::Class::Storage::DBI::Replicated::Replicant>), defines a
22 method by which query load can be spread out across each replicant in the pool.
24 This Balancer uses L<List::Util> keyword 'shuffle' to randomly pick an active
25 replicant from the associated pool. This may or may not be random enough for
30 This class defines the following attributes.
32 =head2 master_read_weight
34 A number greater than 0 that specifies what weight to give the master when
35 choosing which backend to execute a read query on. A value of 0, which is the
36 default, does no reads from master, while a value of 1 gives it the same
37 priority as any single replicant.
39 For example: if you have 2 replicants, and a L</master_read_weight> of C<0.5>,
40 the chance of reading from master will be C<20%>.
42 You can set it to a value higher than 1, making master have higher weight than
43 any single replicant, if for example you have a very powerful master.
47 has master_read_weight => (is => 'rw', isa => PositiveNumber, default => sub { 0 });
51 This class defines the following methods.
55 Returns an active replicant at random. Please note that due to the nature of
56 the word 'random' this means it's possible for a particular active replicant to
57 be requested several times in a row.
64 my @replicants = $self->pool->active_replicants;
66 if (not @replicants) {
67 # will fall back to master anyway
71 my $master = $self->master;
73 my $rnd = $self->_random_number(@replicants + $self->master_read_weight);
75 return $rnd >= @replicants ? $master : $replicants[int $rnd];
82 =head1 FURTHER QUESTIONS?
84 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
86 =head1 COPYRIGHT AND LICENSE
88 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
89 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
90 redistribute it and/or modify it under the same terms as the
91 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.