SOFARegistry 是螞蟻金服開源的一個生產級、高時效、高可用的服務註冊中心java
功能特性node
* 支持服務發佈與服務訂閱 * 支持服務變動時的主動推送 * 豐富的 REST 接口 * 採用分層架構及數據分片,支持海量鏈接及海量數據 * 支持多副本備份,保證數據高可用 * 基於 SOFABolt 通訊框架,服務上下線秒級通知 * AP 架構,保證網絡分區下的可用性
sofa-registry地址:https://github.com/sofastack/sofa-registrygit
其支持服務發佈與服務訂閱
功能,依賴一致性hash算法, 其簡介:參見:https://www.jianshu.com/p/e968c081f563github
在解決分佈式系統中負載均衡的問題時候能夠使用Hash算法讓固定的一部分請求落到同一臺服務器上,這樣每臺服務器固定處理一部分請求(並維護這些請求的信息),起到負載均衡的做用。 可是普通的餘數hash(hash(好比用戶id)%服務器機器數)算法伸縮性不好,當新增或者下線服務器機器時候,用戶id與服務器的映射關係會大量失效。一致性hash則利用hash環對其進行了改進。算法
核心代碼參見:代碼地址:[ConsistentHash.java](https://github.com/sofastack/sofa- registry/blob/master/server/consistency/src/main/java/com/alipay/sofa/registry/consistency/hash/ConsistentHash.java "ConsistentHash.java")服務器
private final SortedMap<Integer, T> circle = new TreeMap<>(); /** * This returns the closest node for the object. If the object is the node it * should be an exact hit, but if it is a value traverse to find closest * subsequent node. * @param key the key * @return node for */ public T getNodeFor(Object key) { if (circle.isEmpty()) { return null; } int hash = hashFunction.hash(key); T node = circle.get(hash); if (node == null) { // inexact match -- find the next value in the circle SortedMap<Integer, T> tailMap = circle.tailMap(hash); hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey(); node = circle.get(hash); } return node; }
獲取大於該node節點對應hash值的的hash環(tailMap方法)信息,即tailMap網絡
tailMap(K fromKey) 方法用於返回此映射,其鍵大於或等於fromKey的部分視圖。 返回的映射受此映射支持,所以改變返回映射反映在此映射中,反之亦然。
新的節點嘗試註冊進來,會調用addNode(T node)
方法,同時會有虛擬節點存在架構
/** * Add a new node to the consistent hash * * This is not thread safe. * @param node the node */ private void addNode(T node) { realNodes.add(node); for (int i = 0; i < numberOfReplicas; i++) { // The string addition forces each replica to have different hash circle.put(hashFunction.hash(node.getNodeName() + SIGN + i), node); } }