一致性哈希算法(C++11实现)

#include <iostream>
#include <string>
#include <stdint.h>
#include <math.h>
#include <stdlib.h>
#include <map>
#include <cmath>
#include <set>
#include <initializer_list>
#include <vector>
#include <algorithm>
//定义哈希反函数对象
template<typename K, typename V> class Hash;
//虚拟节点
template<typename N> class VNode;
//哈希仿函数对象,v为std::string, 映射为uint32_t
template<>
class Hash<std::string, uint32_t> {
public:
    uint32_t operator()(const std::string & key) const {
        int p = 16777619;
        uint32_t hash = 2166136261L;
        for (int i = 0, num = key.size(); i < num; ++i) {
            hash = (hash ^ key[i]) * p;
        }
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;

        if (hash < 0) {
            hash = abs((long)hash);
        }
        return hash;
    }
};
//哈希环算法对象,内部可调用不同哈希算法将node映射到uint32_t
template<typename V>
class HashRingAlgorithm {
public:
    HashRingAlgorithm() {}
    virtual ~HashRingAlgorithm() {}
public:
    uint32_t hash(const V & v) const {
        Hash<V, uint32_t> h;
        return h(v);
    }
};

/*
 * 虚拟节点,模板参数N为server真实节点
*/
template<typename N>
class VNode {
public:
    VNode() {};//just make compiler happy
    VNode(const N & n, uint32_t idx) {
        key_ = std::string(n) + "#" + std::to_string(idx);
        rnode_ = n;
    };

    virtual ~VNode() {

    };

    operator std::string() const {
        return key_;
    }

    N getRNode() const {
        return rnode_;
    }
private:
    std::string key_;
    N rnode_;//真实节点
};


/*
 * 一致性哈希环对象,顶层对象,N为Server类,K为映射key如std::string
*/
template<typename N, typename K>
class ConsitentHashRing {
public:
    ConsitentHashRing(uint32_t vn_count = 1000) {
        vn_count_ = vn_count;
    }

    virtual ~ConsitentHashRing() {
        vnodes_map_.clear();
    }
public:
    void addNode(const N & n) {
        for (uint32_t i = 0; i < vn_count_; i++) {
            VNode<N> vnode(n, i);
            uint32_t hash = hash_algorithm_.hash(vnode);
            vnodes_map_[hash] = vnode;
            real_nodes_.push_back(n);
        }
    }

    N  getNode(const K & v) const {
        uint32_t hash = hash_algorithm_.hash(v);
        auto it = vnodes_map_.lower_bound(hash);
        if (it == vnodes_map_.end()) {
            return vnodes_map_.begin()->second.getRNode();
        }
        return it->second.getRNode();
    }

    int removeNode(const N & n) {
        for (auto it = vnodes_map_.begin(); it != vnodes_map_.end();) {
            if (it->second.getRNode() == n) {
                vnodes_map_.erase(it++);
            }
            else {
                it++;
            }
        }

        for (auto it = real_nodes_.begin(); it != real_nodes_.end(); it++) {
            if (*it == n) {
                real_nodes_.erase(it);
                break;
            }
        }
        return 0;
    }

private:
    uint32_t vn_count_;
    std::map<uint32_t, VNode<N>> vnodes_map_;
    std::vector<N> real_nodes_;
    HashRingAlgorithm<K> hash_algorithm_;
};

class ServerNode {
public:
    ServerNode() {};
    ServerNode(const std::string & host, uint16_t port) {
        host_ = host;
        port_ = port;
    }
    virtual ~ServerNode() {}
        //removeNode时,需要比较,所以需要实现operator==
    bool operator==(const ServerNode & s) const {
        if (s.host_ == host_ && s.port_ == port_) {
            return true;
        }
        return false;
    }
        //哈希映射时,目前使用std::string作为参数,所以需要隐式转换
    operator std::string() const {
        return host_ + ":" + std::to_string(port_);
    }
public:
    std::string host_;
    uint16_t port_;
};

int main(char argc, char *argv[]) {
        //初始化测试
    ConsitentHashRing<ServerNode, std::string> hash_ring;
    hash_ring.addNode(ServerNode("192.168.128.1", 1935));
    hash_ring.addNode(ServerNode("192.168.128.2", 1935));
    hash_ring.addNode(ServerNode("192.168.128.3", 1935));
    hash_ring.addNode(ServerNode("192.168.128.4", 1935));
    hash_ring.addNode(ServerNode("192.168.128.5", 1935));
    hash_ring.addNode(ServerNode("192.168.128.6", 1935));
    hash_ring.addNode(ServerNode("192.168.128.7", 1935));
    hash_ring.addNode(ServerNode("192.168.128.8", 1935));
    hash_ring.addNode(ServerNode("192.168.128.9", 1935));

    int count[10] = { 0 };
    for (int i = 0; i < 10000; i++) {
        int m = rand() % 1000000;
        auto s = hash_ring.getNode(std::to_string(m));
        std::cout << std::string(s) << std::endl;
        if (s.host_ == "192.168.128.1") {
            count[0]++;
        }
        else if (s.host_ == "192.168.128.2") {
            count[1]++;
        }
        else if (s.host_ == "192.168.128.3") {
            count[2]++;
        }
        else if (s.host_ == "192.168.128.4") {
            count[3]++;
        }
        else if (s.host_ == "192.168.128.5") {
            count[4]++;
        }
        else if (s.host_ == "192.168.128.6") {
            count[5]++;
        }
        else if (s.host_ == "192.168.128.7") {
            count[6]++;
        }
        else if (s.host_ == "192.168.128.8") {
            count[7]++;
        }
        else if (s.host_ == "192.168.128.9") {
            count[8]++;
        }
        else if (s.host_ == "192.168.128.10") {
            count[9]++;
        }
    }
    for (int i = 0; i < 10; i++) {
        std::cout << "count[" << i << "] = " << count[i] << std::endl;
        count[i] = 0;
    }
    getchar();
        //添加一个节点测试
    hash_ring.addNode(ServerNode("192.168.128.10", 1935));
    for (int i = 0; i < 10000; i++) {
        int m = rand() % 1000000;
        auto s = hash_ring.getNode(std::to_string(m));
        std::cout << std::string(s) << std::endl;
        if (s.host_ == "192.168.128.1") {
            count[0]++;
        }
        else if (s.host_ == "192.168.128.2") {
            count[1]++;
        }
        else if (s.host_ == "192.168.128.3") {
            count[2]++;
        }
        else if (s.host_ == "192.168.128.4") {
            count[3]++;
        }
        else if (s.host_ == "192.168.128.5") {
            count[4]++;
        }
        else if (s.host_ == "192.168.128.6") {
            count[5]++;
        }
        else if (s.host_ == "192.168.128.7") {
            count[6]++;
        }
        else if (s.host_ == "192.168.128.8") {
            count[7]++;
        }
        else if (s.host_ == "192.168.128.9") {
            count[8]++;
        }
        else if (s.host_ == "192.168.128.10") {
            count[9]++;
        }
    }
    for (int i = 0; i < 10; i++) {
        std::cout << "count[" << i << "] = " << count[i] << std::endl;
        count[i] = 0;
    }

    getchar();
        //删除一个节点测试
    hash_ring.removeNode(ServerNode("192.168.128.10", 1935));
    for (int i = 0; i < 10000; i++) {
        int m = rand() % 1000000;
        auto s = hash_ring.getNode(std::to_string(m));
        std::cout << std::string(s) << std::endl;
        if (s.host_ == "192.168.128.1") {
            count[0]++;
        }
        else if (s.host_ == "192.168.128.2") {
            count[1]++;
        }
        else if (s.host_ == "192.168.128.3") {
            count[2]++;
        }
        else if (s.host_ == "192.168.128.4") {
            count[3]++;
        }
        else if (s.host_ == "192.168.128.5") {
            count[4]++;
        }
        else if (s.host_ == "192.168.128.6") {
            count[5]++;
        }
        else if (s.host_ == "192.168.128.7") {
            count[6]++;
        }
        else if (s.host_ == "192.168.128.8") {
            count[7]++;
        }
        else if (s.host_ == "192.168.128.9") {
            count[8]++;
        }
        else if (s.host_ == "192.168.128.10") {
            count[9]++;
        }
    }
    for (int i = 0; i < 10; i++) {
        std::cout << "count[" << i << "] = " << count[i] << std::endl;
    }
    return 0;
}
测试结果(0-9对应9个服务器):
初始化测试:
count[0] = 1135
count[1] = 1248
count[2] = 1133
count[3] = 1096
count[4] = 1119
count[5] = 1057
count[6] = 992
count[7] = 1155
count[8] = 1065
count[9] = 0
添加一个节点测试:
count[0] = 1012
count[1] = 1061
count[2] = 969
count[3] = 987
count[4] = 1060
count[5] = 986
count[6] = 943
count[7] = 997
count[8] = 974
count[9] = 1011
删除一个节点测试:
count[0] = 1097
count[1] = 1208
count[2] = 1112
count[3] = 1101
count[4] = 1103
count[5] = 1093
count[6] = 1053
count[7] = 1159
count[8] = 1074
count[9] = 0
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,692评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,482评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,995评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,223评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,245评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,208评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,091评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,929评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,346评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,570评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,739评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,437评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,037评论 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,677评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,833评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,760评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,647评论 2 354