// main函数
# 创建HASH RING
pstHashRing = HashRingCreate(RING_SIZE);
if (!pstHashRing)
return -1;
# 添加节点
for (i = 0; i < gwNodeNum; i++)
{
pstNode = HashRingNodeCreate(i, DEFAULT_VNODE_NUM, NULL);
HashRingAddNode(pstHashRing, pstNode);
pNodeList[i] = pstNode;
}
// HashRIngAddNode实现:
void HashRingAddNode(HashRing *pstHashRing, HashNode *pstNode)
{
unsigned int i, j, k;
unsigned int wTarget;
unsigned int wVNodeNum;
if (pstHashRing == NULL || pstNode == NULL || pstNode->wVNodeNum == 0)
return;
wVNodeNum = pstNode->wVNodeNum;
if (pstHashRing->wNodeNum + wVNodeNum > pstHashRing->wRingSize)
{
printf("HashRing is full! current/size: [%d/%d], need [%d]!\n", \
pstHashRing->wNodeNum, pstHashRing->wRingSize, wVNodeNum);
return;
}
for (i = 0; i < wVNodeNum; i++)
{
// 产生随机数
k = random_uint(pstHashRing->wRingSize);
// 已经有节点,顺序查找空节点
if (pstHashRing->pRingArray[k])
{
for (j = 1; j < pstHashRing->wRingSize; j++)
{
k = (k + j);
if (k > pstHashRing->wRingSize)
k = k%pstHashRing->wRingSize;
if (pstHashRing->pRingArray[k] == NULL)
{
wTarget = k;
break;
}
}
}
else
wTarget = k;
// 添加到HashRing - 对节点赋值
pstHashRing->pRingArray[wTarget] = pstNode;
pstHashRing->wNodeNum++;
//printf("Add node[%d_%d] to ring posite [%d]\n", pstNode->wId, i, wTarget);
}
}
评论