方法1,hash后取模:
<?php
function get_hash($str, $num=10){
$crc = crc32($str);
$nu = $crc % $num;
return $nu;
}
测试公平性:
<?php
function genstr($num) {
return substr(str_shuffle('abcdefghijklmnupqrstuvwxyz'), 0, $num);
}
for ($i=1; $i<10000000; $i++) {
$str = genstr(5);
$crc = crc32($str);
$nu = get_hash($str);;
if (isset($count[$nu])) {
$count[$nu]++;
} else {
$count[$nu]=1;
}
}
print_r($count);
方法2,动态增添后最小影响之前的hash结果可使用consistent hashing:
https://github.com/RJ/ketama
https://github.com/pda/flexihash
标签:none