3

私のウェブサイトでは、単一のドメインからさまざまなリソースを使用しています。たとえば、次のようになります。

http://static.example.com/javascript/common.js
http://static.example.com/javascript/common.css
http://static.example.com/javascript/menu/menu.js
http://static.example.com/javascript/menu/menu.css
http://static.example.com/images/1804/logo/02000100.jpg
http://static.example.com/images/1804/headers/main/09400060.png
http://static.example.com/images/1804/headers/home/1101/06900200-01.jpg
http://static.example.com/images/1804/headers/home/1101/06900200-02.jpg

これらの URL を数字 (0、1、2、3) にマップする非常に単純な文字列ハッシュ関数が必要です。アルゴリズムは決定論的で統一されている必要があります。質問 PHP にタグを付けましたが、一般的な回答は受け入れられます。

なぜこれが必要なのか、ご想像のとおりです。たとえば、次のように URL を変更する予定です。

http://0.static.example.com/javascript/common.js
http://2.static.example.com/javascript/common.css
4

2 に答える 2

2

crc32私は文字列のハッシュを実行し、そのモジュロを制限付きで取得することを好みます。

コード:

function numeric_hash($str, $range) {
    return sprintf("%u", crc32($str)) % $range;
}

使用法:

$str = "http://static.example.com/javascript/common.js
http://static.example.com/javascript/common.css
http://static.example.com/javascript/menu/menu.js
http://static.example.com/javascript/menu/menu.css
http://static.example.com/images/1804/logo/02000100.jpg
http://static.example.com/images/1804/headers/main/09400060.png
http://static.example.com/images/1804/headers/home/1101/06900200-01.jpg
http://static.example.com/images/1804/headers/home/1101/06900200-02.jpg";
$urls = explode("\n", $str);

foreach($urls as $url) {
    echo numeric_hash($url, 4) . "\n";
}

出力:

1
3
3
3
1
3
1
3
于 2012-11-16T10:29:31.217 に答える
1

URLがたくさんある場合は、強力なハッシュを実行してから、mod <noBuckets>

MD5(URL) % 4

URLが少ない場合、サイズや呼び出し頻度が不均一な場合は、「ランダム」な分散が適切でない可能性があります。手動で、またはURLあたりのリクエスト数に基づくヒューリスティックを使用して、4つのリストを作成し、各リストにURLを静的に割り当てる必要があります。 。

于 2012-11-16T10:27:50.910 に答える