<?php
class Test
{
public const virtualHostNode = 100;
public const HOST_MAP = [
"http://img1.baidu.com",
"http://img2.baidu.com",
"http://img3.baidu.com",
"http://img4.baidu.com",
"http://img5.baidu.com",
];
public static $servers = null;
public static function getHashModId(string $val)
{
$res = sprintf("%u", crc32(md5($val)));
return $res % 4294967295;
}
public static function getServers()
{
$result = [];
foreach (self::HOST_MAP as $url) {
for ($i = 1; $i <= self::virtualHostNode; $i++) {
$result[self::getHashModId("{$url}_{$i}")] = $url;
}
}
ksort($result);
self::$servers = $result;
}
public static function getServer(string $key)
{
$servers = self::$servers;
if (empty($servers)) {
return;
}
$hashMod = self::getHashModId($key);
$nowUrl = '';
foreach ($servers as $id => $url) {
if ($hashMod <= $id) {
$nowUrl = $url;
break;
}
}
if (empty($nowUrl)) {
$nowUrl = current($servers);
}
return $nowUrl;
}
}
$tt = new Test();
$servers = $tt->getServers();
$weight = [];
for ($i = 1; $i <= 1000000; $i++) {
$fileName = "test00{$i}.jpg";
$url = $tt->getServer($fileName);
$weight[] = $url;
}
$total = count($weight);
$arrayCount = array_count_values($weight);
foreach ($arrayCount as $url => $num) {
$p = bcmul(bcdiv($num, $total, 6), 100, 2);
echo "{$url}占比:{$p}%
";
}