::DBI::Replicated - add master_read_weight to ::Random balancer_type
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / Storage / DBI / Replicated / Balancer / Random.pm
CommitLineData
cb6ec758 1package DBIx::Class::Storage::DBI::Replicated::Balancer::Random;
2
cb6ec758 3use Moose;
17b05c13 4with 'DBIx::Class::Storage::DBI::Replicated::Balancer';
ee356d00 5use DBIx::Class::Storage::DBI::Replicated::Types 'Weight';
41916570 6use namespace::clean -except => 'meta';
cb6ec758 7
8=head1 NAME
9
f09cd1d4 10DBIx::Class::Storage::DBI::Replicated::Balancer::Random - A 'random' Balancer
cb6ec758 11
12=head1 SYNOPSIS
13
14This class is used internally by L<DBIx::Class::Storage::DBI::Replicated>. You
15shouldn't need to create instances of this class.
16
17=head1 DESCRIPTION
18
19Given a pool (L<DBIx::Class::Storage::DBI::Replicated::Pool>) of replicated
20database's (L<DBIx::Class::Storage::DBI::Replicated::Replicant>), defines a
21method by which query load can be spread out across each replicant in the pool.
22
23This Balancer uses L<List::Util> keyword 'shuffle' to randomly pick an active
24replicant from the associated pool. This may or may not be random enough for
25you, patches welcome.
26
27=head1 ATTRIBUTES
28
29This class defines the following attributes.
30
ee356d00 31=head2 master_read_weight
32
33A number from 0 to 1 that specifies what weight to give the master when choosing
34which backend to execute a read query on. A value of 0, which is the default,
35does no reads from master, while a value of 1 gives it the same priority as any
36single replicant.
37
38=cut
39
40has master_read_weight => (is => 'rw', isa => Weight, default => sub { 0 });
41
cb6ec758 42=head1 METHODS
43
44This class defines the following methods.
45
46=head2 next_storage
47
48Returns an active replicant at random. Please note that due to the nature of
49the word 'random' this means it's possible for a particular active replicant to
50be requested several times in a row.
51
52=cut
53
54sub next_storage {
c354902c 55 my $self = shift @_;
ee356d00 56
57 my @replicants = $self->pool->active_replicants;
58 my $master = $self->master;
59
60 my $rnd = $self->random_number(@replicants + $self->master_read_weight);
61
62 return $rnd >= @replicants ? $master : $replicants[int $rnd];
63}
64
65=head2 random_number
66
67Returns a random number from 0 to x, not including x. Uses perl's
68L<perlfunc/rand> by default.
69
70=cut
71
72sub random_number {
73 rand($_[1])
cb6ec758 74}
75
cb6ec758 76=head1 AUTHOR
77
78John Napiorkowski <john.napiorkowski@takkle.com>
79
80=head1 LICENSE
81
82You may distribute this code under the same terms as Perl itself.
83
84=cut
85
c354902c 86__PACKAGE__->meta->make_immutable;
87
41916570 881;