Subject: | the number of buckets should be configurable |
Hi,
This patch enables you to change the number of buckets with the new
method set_num_buckets().
In order to distribute buckets uniformly among targets (servers), the
number of buckets must be greater than 100 * (average weight) * (# targets).
The current setting (1024) is too small, when there are several tens of
targets.
Regards,
Subject: | Set-ConsistentHash.pm-num_buckets.patch |
--- lib/Set/ConsistentHash.pm-orig 2007-04-27 07:11:43.000000000 +0900
+++ lib/Set/ConsistentHash.pm 2008-02-09 14:17:59.000000000 +0900
@@ -60,6 +60,7 @@
weights => {}, # $target => integer $weight
points => {}, # 32-bit value points on 'circle' => \$target
order => [], # 32-bit points, sorted
+ num_buckets => 1024, # the number of buckets
buckets => undef, # when requested, arrayref of 1024 buckets mapping to targets
total_weight => undef, # when requested, total weight of all targets
hash_func => undef, # hash function for key lookup
@@ -212,6 +213,22 @@
############################################################################
+=head2 set_num_buckets
+
+ $set->set_num_buckets($num_buckets);
+
+Sets the number of buckets, which should be 2^n and greater than
+100 * (average weight) * (# targets).
+
+=cut
+
+sub set_num_buckets {
+ my ($self, $num_buckets) = @_;
+ $self->{num_buckets} = $num_buckets;
+}
+
+############################################################################
+
=head2 get_target
$selected_target = $set->get_target(your_hash_func($your_key));
@@ -232,7 +249,7 @@
my ($self, $key) = @_;
_compute_buckets($self) unless $self->{buckets};
$key = $self->{hash_func}->($key) if $self->{hash_func};
- return $self->{buckets}->[$key % 1024];
+ return $self->{buckets}->[$key % $self->{num_buckets}];
}
=head2 buckets
@@ -273,9 +290,9 @@
sub _compute_buckets {
my $self = shift;
my @buckets = ();
- my $by = 2**22; # 2**32 / 2**10 (1024)
+ my $by = (2**32 / $self->{num_buckets});
my $pt = 0;
- for my $n (0..1023) {
+ for my $n (0..($self->{num_buckets}-1)) {
$buckets[$n] = $self->target_of_point($pt);
$pt += $by;
}