写点什么

第 5 周:作业一

用户头像
远方
关注
发布于: 2020 年 07 月 08 日

一致性哈希类

public class ConsistentHash {



private static SortedMap<Long, String> virtualNodes = new TreeMap<Long, String>();

// private static Map<String, String> map = new HashMap<>();

private static Map<String, Integer> serIndex = new HashMap<>();

private int num = 10;



public ConsistentHash(int num){

this.num = num;

init();

}



private void init(){

String ser = "ser_";

for(int i=0;i<num;i++){

String serTmp = ser + "_" + i;

add(serTmp);

serIndex.put(serTmp, i);

}

}



public void add(String ser){

long size = (long)1024 1024 1024 * 4;

for(int j=0;j<200;j++){

String serTmp = ser + "_" + j;

long serPos = Math.abs((long)this.hash(serTmp) % size);

virtualNodes.put(serPos, ser);

}

}



public void remove(String ser){

long size = (long)1024 1024 1024 * 4;

for(int j=0;j<200;j++){

String serTmp = ser + "_" + j;

long serPos = Math.abs((long)this.hash(serTmp) % size);

virtualNodes.remove(serPos);

}

}



public int getServer(String key){

SortedMap<Long, String> sortedMap = null;

long keyPos = -1;

Long serKey = (long)0;

try {

long size = (long)1024 1024 1024 * 4;

keyPos = Math.abs((long)this.hash(key) % size);

sortedMap = virtualNodes.tailMap(keyPos);

if(null != sortedMap && sortedMap.size() > 0){

serKey = sortedMap.firstKey();

}else {

serKey = virtualNodes.firstKey();

}

String server = virtualNodes.get(serKey);



return serIndex.get(server);

} catch (Exception e) {

e.printStackTrace();

throw e;

} finally {

}



}



public Integer hash(String key) {



final int p = 16777619;

int hash = (int)2166136261L;

for (int i = 0; i < key.length(); i++)

hash = (hash ^ key.charAt(i)) * p;

hash += hash << 13;

hash ^= hash >> 7;

hash += hash << 3;

hash ^= hash >> 17;

hash += hash << 5;



// 如果算出来的值为负数则取其绝对值

if (hash < 0)

hash = Math.abs(hash);

return hash;

}

}



用例:求标准差

public class OneHash2 {



//标准差σ=sqrt(s^2)

public static double StandardDiviation(Integer[] x) {

int m=x.length;

double sum=0;

for(int i=0;i<m;i++){//求和

sum+=x[i];

}

double dAve=sum/m;//求平均值

double dVar=0;

for(int i=0;i<m;i++){//求方差

dVar+=(x[i]-dAve)*(x[i]-dAve);

}

//reture Math.sqrt(dVar/(m-1));

return Math.sqrt(dVar/m);

}



public static void main(String[] args) {



ConsistentHash consistentHash = new ConsistentHash(10);

Integer[] arr = new Integer[1000* 1000];

String key = "key";

for(int i=0;i<1000000;i++){

// System.out.println(i);

key = UUID.randomUUID().toString() + "_" + i;

int serIndex = consistentHash.getServer(key);

arr[i] = serIndex;

// System.out.println(serIndex);

}



double rs = OneHash2.StandardDiviation(arr);

System.out.println(rs);

}

}



用户头像

远方

关注

还未添加个人签名 2018.03.12 加入

还未添加个人简介

评论

发布
暂无评论
第5周:作业一