# loop_in_codes

## Round-robin

``````curId = ++curId % nodeCnt
``````

## 随机选择

``````id = random(nodeCnt);
``````

## 本机优先

``````if (node->ip() == local_ip) {
return node;
} else {
return roundRobin();
}
``````

``````// initial
cur_weight = 100;
...
// select node
cur_weight -= 5;
if (cur_weight <= 0)
cur_weight = 100;
if (cur_weight > 50 && node->ip() == local_ip) {
return node;
} else {
return roundRobin();
}
``````

## Weighted Round-Robin

``````假设有一组服务器S = {S0, S1, …, Sn-1}，W(Si)表示服务器Si的权值，一个

while (true) {
i = (i + 1) mod n;
if (i == 0) {
cw = cw - gcd(S);
if (cw <= 0) {
cw = max(S);
if (cw == 0)
return NULL;
}
}
if (W(Si) >= cw)
return Si;
}
``````

## Consistent Hash

``````// 添加一个物理节点时，会随之增加很多虚拟节点
template <class Node, class Data, class Hash>
size_t HashRing<Node, Data, Hash>::AddNode(const Node& node)
{
size_t hash;
std::string nodestr = Stringify(node);
for (unsigned int r = 0; r < replicas_; r++) {
hash = hash_((nodestr + Stringify(r)).c_str());
ring_[hash] = node;  // 物理节点和虚拟节点都保存在一个std::map中
}
return hash;
}

// 选择data对应的节点，data可以是请求
template <class Node, class Data, class Hash>
const Node& HashRing<Node, Data, Hash>::GetNode(const Data& data) const
{
if (ring_.empty()) {
throw EmptyRingException();
}
size_t hash = hash_(Stringify(data).c_str()); // 对请求进行哈希
typename NodeMap::const_iterator it;
// Look for the first node >= hash
it = ring_.lower_bound(hash); // 找到第一个不小于请求哈希的节点
if (it == ring_.end()) {
// Wrapped around; get the first node
it = ring_.begin();
}
return it->second;
}
``````

posted on 2014-08-26 00:11 Kevin Lynx 阅读(3803) 评论(0)  编辑 收藏 引用 所属分类: network