nginx负载均衡302跳转设置,基于perl的一致性哈希。
目的:降低 后端大文件服务器由于新增和故障调整的影响
通过nginx的perl_module来实现302,根据请求的哈希跳转crc32校验
工作环境: perl版本在>=5.10.0 nginx版本 >==0.8.33 二点必要
rewrite.pm 配置
package rewrite;
use nginx;
use Hash::ConsistentHash;
use String::CRC32;
sub handler {
my $r = shift;
my $uri = $r->uri;
my $domain = $r->header_in(host);
my @crr = qw( 10.0.0.1 10.0.0.2 10.0.0.3 10.0.0.4 10.0.0.5 );
my $chash = Hash::ConsistentHash->new(
buckets => [@crr],
hash_func => &crc32
);
my $url = $chash->get_bucket($uri);
$url = "http://".$url."/".$domain.$uri;
$r->header_out(Location => $url);
$r->status(302);
$r->send_http_header;
return OK;
}
1;
__END__
nginx server 配置
nginx conf配置(加2行)
perl_modules perl/lib;
perl_require rewrite.pm;
由于Hash::ConsistentHash对perl要求版本>=5.10.0,如果你系统perl较低需升级perl版本并重新编译nginx;
Hash::ConsistentHash 下载地址
http://search.cpan.org/CPAN/authors/id/K/KA/KARAVELOV/Hash-ConsistentHash-0.05.tar.gz
String::CRC32下载地址
http://search.cpan.org/CPAN/authors/id/S/SO/SOENKE/String-CRC32-1.4.tar.gz