-
Notifications
You must be signed in to change notification settings - Fork 0
/
LoadBalanceWeightedRandom.h
74 lines (62 loc) · 1.51 KB
/
LoadBalanceWeightedRandom.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
// Load Balance with Weight Random
// Yuchuan Wang
// yuchuan.wang@gmail.com
#pragma once
#include <vector>
#include <string>
#include <unordered_map>
#include <iostream>
#include <algorithm>
class LoadBalanceWeightedRandom
{
public:
LoadBalanceWeightedRandom()
{
}
~LoadBalanceWeightedRandom()
{
}
bool AddServer(const std::string& srv, int weight)
{
if(weight < 1)
{
std::cout << "Weight should be equal or greater than 1." << std::endl;
return false;
}
for(int i = 0; i < weight; i++)
{
// Add weight times to vector
servers.push_back(srv);
}
return true;
}
// Simulate a new request
bool NextRequest()
{
if(servers.empty())
{
std::cout << "Please add servers first. " << std::endl;
return false;
}
// Pickup a random server
int current = rand() % servers.size();
// Update stats
stats[servers[current]]++;
return true;
}
void PrintStats() const
{
std::cout << "Server Hit stats with weighted random: ";
for(auto x : stats)
{
std::cout << std::endl;
std::cout << x.first << ": " << x.second;
}
std::cout << std::endl;
}
private:
// The servers to be balanced
std::vector<std::string> servers;
// Stats, key is the server, value is the hit count
std::unordered_map<std::string, int> stats;
};