publicConsistentHashV1(List<String> nodeList) { Assert.notEmpty(nodeList, "nodeList can not be empty!"); for (String node : nodeList) { addNode(node); } }
/** * 新增node */ publicvoidaddNode(String node) { Assert.hasText(node, "node can not be blank!"); for (inti=0; i < VIRTUAL_NODE_NUM; i++) { StringtmpNode= node + "#" + i; hashCircle.put(HashCodeUtils.hashString(tmpNode), node); } }
/** * 删除node */ publicvoidremoveNode(String node) { Assert.hasText(node, "node can not be blank!"); for (inti=0; i < VIRTUAL_NODE_NUM; i++) { StringtmpNode= node + "#" + i; hashCircle.remove(HashCodeUtils.hashString(tmpNode)); } }
publicConsistentHashV4(List<String> nodeList) { Assert.notEmpty(nodeList, "nodeList can not be empty!"); for (String node : nodeList) { addNode(node); } }
/** * 新增node */ publicvoidaddNode(String node) { Assert.hasText(node, "node can not be blank!"); lock.writeLock().lock(); try { for (inti=0; i < VIRTUAL_NODE_NUM; i++) { StringtmpNode= node + "#" + i; hashCircle.put(HashCodeUtils.hashString(tmpNode), node); } } finally { lock.writeLock().unlock(); } }
/** * 删除node */ publicvoidremoveNode(String node) { Assert.hasText(node, "node can not be blank!"); lock.writeLock().lock(); try { for (inti=0; i < VIRTUAL_NODE_NUM; i++) { StringtmpNode= node + "#" + i; hashCircle.remove(HashCodeUtils.hashString(tmpNode)); } } finally { lock.writeLock().unlock(); } }
/** * 分发 * * @param target * @return */ public String dispatchToNode(String target) { Assert.hasText(target, "target can not be blank!"); lock.readLock().lock(); try { LongtargetHashcode= HashCodeUtils.hashString(target); Longkey= hashCircle.ceilingKey(targetHashcode); if (null == key) { key = hashCircle.firstKey(); } return hashCircle.get(key); } finally { lock.readLock().unlock(); } }