zoukankan      html  css  js  c++  java
  • hash

    
    <?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}%
    ";
    }
    
    
    
  • 相关阅读:
    Nmap笔记
    Spring AOP(一)
    Spring IOC(三)
    Spring IOC(二)
    Spring IOC(一)
    bootstrap 使用(三)
    bootstrap 使用(二)
    bootstrap 使用(一)
    js(二)
    QQ邮件
  • 原文地址:https://www.cnblogs.com/zhanghuizong/p/12779576.html
Copyright © 2011-2022 走看看