架构师训练营第五周作业

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

作业:1.用你熟悉的编程语言实现一致性hash算法

2.编写测试用例测试这个算法,测试100万KV数据,10个服务器节点情况下,计算这些KV数据在服务器上分布数量的标准差。

package connsistent;



import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class ConsistentHash {
TreeMap<Integer, Cache> map = new TreeMap<>();
List<Cache> servers = new ArrayList<>();

public ConsistentHash(List<Cache> servers) {
this.servers = servers;
}

public void addServers(String[] servers, int virtualNo) {
if (servers != null) {
for (String server : servers) {
Cache cacheServer = (Cache) new CacheServer(server);
map.put(hashCode(server), cacheServer);
for (int i = 1; i <= virtualNo; i++) {
map.put(getVirutalHashCode(server, i), cacheServer);
}

this.servers.add(cacheServer);
}
}
}

private int getVirutalHashCode(String key, int i) {
key = key + "&&Virtual" + i;
return hashCode(key);
}

public static int hashCode(String key) {
final int p = 16777619;
int ret = (int) 2166136261L;
for (int i = 0; i < key.length(); i++) {
ret = (ret ^ key.charAt(i)) * p;
}
ret += ret << 13;
ret ^= ret >> 7;
ret += ret << 3;
ret ^= ret >> 17;
ret += ret << 5;

return ret < 0 ? -ret : ret;
}

}





package connsistent;

import cn.beinet.Cache;

import java.util.HashMap;
import java.util.Map;

public class CacheServer implements Cache {
private Map<String, String> caches = new HashMap<>();

private String serverName;

public CacheServer(String serverName) {
this.serverName = serverName;
}

public String getServerName() {
return serverName;
}

public Map<String, String> getCaches() {
return caches;
}

@Override
public String get(String key) {
return caches.get(key);
}

@Override
public void set(String key, String val) {
caches.put(key, val);
}
}




package connsistent;

public interface Cache {

String get(String key);

void set(String key, String val);
}



用户头像

hiqian

关注

还未添加个人签名 2018.12.04 加入

还未添加个人简介

评论

发布
暂无评论
架构师训练营第五周作业