写点什么

Week5 作业 1

用户头像
shuyaxx
关注
发布于: 2020 年 11 月 22 日

/**

* Created by Sean on 2020/11/22.

*/

import java.util.Random;

import java.util.SortedMap;

import java.util.TreeMap;

import java.util.UUID;



public class HashApp {

// 8台机器

private static String[] servers = {"192.168.0.0:111", "192.168.0.1:111", "192.168.0.2:111",

"192.168.0.3:111", "192.168.0.4:111"};



private static SortedMap serverNodes;



static {

serverNodes = new TreeMap<Integer, String>();

int len=servers.length;

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

int hashCode = getHashCode(servers[i]);

serverNodes.putIfAbsent(hashCode, servers[i]);

}

}



// 通过client_ip的哈希值路由一个虚拟节点,再映射到物理节点

public static String getServer(String dataName) {

int hashCode = getHashCode(dataName);

SortedMap subMap = serverNodes.tailMap(hashCode);

int firstKey = 0;

firstKey=(Integer)subMap.firstKey();

String virtualNode = (String)subMap.get(firstKey);

// 模拟寻找物理节点,把vni去掉

System.out.println( "dataName :"+dataName + " in nodeName : "+ virtualNode);

return virtualNode;

}



// 使用32位FNV_1

private static int getHashCode(String node) {

final int p = 16777619;

int hash = (int)2166136261L;

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

hash = (hash ^ node.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 static void main(String[] args)

{



String[] nodes = {"127.0.0.1:1111", "221.226.0.1:2222", "10.211.0.1:3333"};

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

System.out.println("[" + nodes[i] + "]的hash值为" +

getHashCode(nodes[i]) + ", 被路由到结点[" + getServer(nodes[i]) + "]");

}



}

用户头像

shuyaxx

关注

还未添加个人签名 2018.06.23 加入

还未添加个人简介

评论

发布
暂无评论
Week5 作业1