1 package DBIx::Class::Storage::DBI::Replicated::Balancer::Random;
4 with 'DBIx::Class::Storage::DBI::Replicated::Balancer';
5 use DBIx::Class::Storage::DBI::Replicated::Types 'Weight';
6 use namespace::clean -except => 'meta';
10 DBIx::Class::Storage::DBI::Replicated::Balancer::Random - A 'random' Balancer
14 This class is used internally by L<DBIx::Class::Storage::DBI::Replicated>. You
15 shouldn't need to create instances of this class.
19 Given a pool (L<DBIx::Class::Storage::DBI::Replicated::Pool>) of replicated
20 database's (L<DBIx::Class::Storage::DBI::Replicated::Replicant>), defines a
21 method by which query load can be spread out across each replicant in the pool.
25 This class defines the following attributes.
27 =head2 master_read_weight
29 A number greater than 0 that specifies what weight to give the master when
30 choosing which backend to execute a read query on. A value of 0, which is the
31 default, does no reads from master, while a value of 1 gives it the same
32 priority as any single replicant.
34 For example: if you have 2 replicants, and a L</master_read_weight> of C<0.5>,
35 the chance of reading from master will be C<20%>.
37 You can set it to a value higher than 1, making master have higher weight than
38 any single replicant, if for example you have a very powerful master.
42 has master_read_weight => (is => 'rw', isa => Weight, default => sub { 0 });
46 This class defines the following methods.
50 Returns an active replicant at random. Please note that due to the nature of
51 the word 'random' this means it's possible for a particular active replicant to
52 be requested several times in a row.
59 my @replicants = $self->pool->active_replicants;
61 if (not @replicants) {
62 # will fall back to master anyway
66 my $master = $self->master;
68 my $rnd = $self->_random_number(@replicants + $self->master_read_weight);
70 return $rnd >= @replicants ? $master : $replicants[int $rnd];
77 =head1 FURTHER QUESTIONS?
79 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
81 =head1 COPYRIGHT AND LICENSE
83 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
84 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
85 redistribute it and/or modify it under the same terms as the
86 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
90 __PACKAGE__->meta->make_immutable;