Skip to content

Commit 317a56a

Browse files
committed
一致性hash算法
1 parent 0da84bb commit 317a56a

File tree

2 files changed

+125
-0
lines changed

2 files changed

+125
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
<?php
2+
3+
/**
4+
*
5+
* Created by PhpStorm.
6+
* Author: evolution
7+
* Date: 16-7-8
8+
* Time: 上午9:33
9+
*
10+
* license GPL
11+
*/
12+
class MemServerSetting
13+
{
14+
//hashtable size
15+
private $size = 100;
16+
private static $instance;
17+
private $memServer=[];
18+
19+
/**
20+
* 初始化hash表
21+
*
22+
*/
23+
private function __construct(){
24+
//部署缓存服务器
25+
$this->setMemServer();
26+
//设置缓存服务器的个数
27+
$this->size = count($this->memServer);
28+
}
29+
30+
private function __clone(){
31+
echo 'not instance';
32+
}
33+
34+
/**
35+
* 部署缓存服务器
36+
*
37+
* @author: jichao.wang <[email protected]>
38+
*/
39+
private function setMemServer(){
40+
$this->memServer = [
41+
['host'=>'192.168.1.123', 'port'=>6379],
42+
['host'=>'192.168.1.321', 'port'=>6379],
43+
];
44+
}
45+
46+
/**
47+
* 选择合适的缓存服务器
48+
*
49+
* @author: jichao.wang <[email protected]>
50+
*
51+
* @param $key
52+
*/
53+
public function getMemServer($key){
54+
$index = $this->hashFunc($key);
55+
return $this->memServer[$index];
56+
}
57+
58+
/**
59+
* 获取一个缓存服务的实例
60+
*
61+
* @author: jichao.wang <[email protected]>
62+
*/
63+
static public function getInstance(){
64+
if(empty(self::$instance)){
65+
self::$instance = new MemServerSetting();
66+
}
67+
68+
return self::$instance;
69+
}
70+
71+
/**
72+
* hash 函数
73+
*
74+
* @author: jichao.wang <[email protected]>
75+
*
76+
* @param $key
77+
*
78+
* @return int
79+
*/
80+
private function hashFunc($key){
81+
$sum = crc32($key);
82+
return $sum % $this->size;
83+
}
84+
85+
}

consistency_hash/index.php

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
/**
3+
* Created by PhpStorm.
4+
* Author: evolution
5+
* Date: 16-7-8
6+
* Time: 下午4:26
7+
*
8+
* license GPL
9+
*/
10+
include_once "MemServerSetting.php";
11+
$mObj = MemServerSetting::getInstance();
12+
print_r($mObj->getMemServer('name'));
13+
print_r($mObj->getMemServer('age'));
14+
print_r($mObj->getMemServer('sex'));
15+
16+
function chash($key){
17+
$md5 = substr(md5($key),0,8);
18+
echo $md5;
19+
$seed = 31;
20+
$hash = 0;
21+
22+
for($i = 0; $i<8;$i++){
23+
$hash = $hash*$seed + ord($md5{$i});
24+
}
25+
26+
echo "\r\n";
27+
echo $hash;
28+
echo "\r\n";
29+
echo "crc32:".crc32($key);
30+
echo "\r\n";
31+
return $hash & 0x7FFFFFFF;
32+
}
33+
34+
echo chash('name');
35+
echo "\r\n";
36+
echo 2740435799612 & 0x7FFFFFFF;
37+
echo bindec(100111111000001110101100111100111000111100 & 1111111111111111111111111111111);
38+
echo "\r\n";
39+
echo "end";
40+
echo "\r\n";

0 commit comments

Comments
 (0)