-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoadBalanceConsistentHashing.h
124 lines (105 loc) · 2.99 KB
/
LoadBalanceConsistentHashing.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// Load Balance with Consistent Hashing
// Yuchuan Wang
// yuchuan.wang@gmail.com
#pragma once
#include <vector>
#include <string>
#include <sstream>
#include <map>
#include <unordered_map>
#include <iostream>
class LoadBalanceConsistentHashing
{
public:
LoadBalanceConsistentHashing(int vNum = 32)
{
virtualNum = vNum;
}
~LoadBalanceConsistentHashing()
{
}
bool AddServer(const std::string& srv)
{
servers.push_back(srv);
// Insert virtual nodes for each real server
for(int i = 0; i < virtualNum; i++)
{
// Compose name like: 192.168.1.10#1
std::stringstream srvName;
srvName << srv << "#" << i;
unsigned int hashKey = std::hash<std::string>{}(srvName.str());
nodes.insert({hashKey, srv});
}
return true;
}
bool DeleteServer(const std::string& srv)
{
auto server = std::find(servers.begin(), servers.end(), srv);
if(server == servers.end())
{
std::cout << "Invalid server to delete. " << std::endl;
return false;
}
// Delete from real servers
servers.erase(server);
// Delete virtual nodes for this real server
for(int i = 0; i < virtualNum; i++)
{
// Compose name like: 192.168.1.10#1
std::stringstream srvName;
srvName << srv << "#" << i;
unsigned int hashKey = std::hash<std::string>{}(srvName.str());
// Find and delete
auto it = nodes.find(hashKey);
if(it != nodes.end())
{
nodes.erase(it);
}
}
return true;
}
// Simulate a new request
bool NextRequest()
{
if(servers.empty())
{
std::cout << "Please add servers first. " << std::endl;
return false;
}
// Find the node for this request
int val = rand();
unsigned int hashKey = std::hash<std::string>{}(std::to_string(val));
auto node = nodes.lower_bound(hashKey);
if(node == nodes.end())
{
// Use the first node if not found
node = nodes.begin();
}
// Update stats
stats[node->second]++;
return true;
}
void ResetStats()
{
stats.clear();
}
void PrintStats() const
{
std::cout << "Server Hit stats with Consistent Hashing: ";
for(auto x : stats)
{
std::cout << std::endl;
std::cout << x.first << ": " << x.second;
}
std::cout << std::endl;
}
private:
// Virtual nodes number for each real server
int virtualNum;
// The real servers
std::vector<std::string> servers;
// The virtual servers. Key is hash, value is the real server
std::map<unsigned int, std::string> nodes;
// Stats, key is the real server, value is the hit count
std::unordered_map<std::string, int> stats;
};