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); } }