阿里巴巴的分布式应用框架-dubbo负载均衡策略--- 一致哈希算法

来源:互联网 发布:史记的地位 知乎 编辑:程序博客网 时间:2024/04/30 20:20

  1.  dubbo负载均衡策略一致哈希算法源码

        dubbo是阿里巴巴公司开发的一个开源分布式应用框架,基于服务的发布者和订阅者,服务者启动服务向注册中心发布自己的服务;消费者(订阅者)启动服务器向注册中心订阅所需要的服务。注册中心将订阅的服务注册列表返回给订阅者。注册中心会感应服务的提供者的变化,如果服务的提供者发生变化,注册中心会立即通知消费者及时变更服务信息数据;dubbo并且带有审计功能--监控中心,服务的发布者和服务的消费者每分钟间隔都会向监控中心发送自己的统计情况如:调用次数 或者调用时间等(这些数据是保存在内存中以每分钟为单位向监控中心进行发送数据)。监控中心宕机不影响使用,只是减少部分采样的数据,对等的集群任意一台服务宕机,会自动切换到其他对等的机器,注册中心宕机,对服务没有影响,订阅者自己本地会缓存服务提供者的列表信息,由此可见dubbo的健壮性还是可以的。

           dubbo有很多非常好的特性:负载均衡、集群容错等

    集群容错策略:

    failover :失败重连;

    failfast:只发起一次请求;

    failsafe:失败直接忽略;

    failback:失败返回定时发送;、

    forking:并发执行 只要有一台成功立即返回;

    broadcast:调用所有提供者任意一台报错就报错)。

     

    负载均衡:

     

      随机按照权重概率选择

      轮循,按公约后的权重设置轮循比率

    • 最少活跃调用数,相同活跃数的随机,活跃数指调用前后计数差。
    • 一致哈希:相同的请求参数会请求同一个服务提供者。

    支持多协议:

    dubbo、thrift、rmi、jms、redis 等。

     

    下面我们看下dubbo的一直哈希策略的实现源代码:默认有160个虚拟节点 这样让服务列表更加均匀分布,命中更均匀。/*

     

  2.  * Copyright 1999-2012 Alibaba Group. 
  3.  *   
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  *   
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  *   
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16. package com.alibaba.dubbo.rpc.cluster.loadbalance;  
  17.   
  18. import java.io.UnsupportedEncodingException;  
  19. import java.security.MessageDigest;  
  20. import java.security.NoSuchAlgorithmException;  
  21. import java.util.List;  
  22. import java.util.SortedMap;  
  23. import java.util.TreeMap;  
  24. import java.util.concurrent.ConcurrentHashMap;  
  25. import java.util.concurrent.ConcurrentMap;  
  26.   
  27. import com.alibaba.dubbo.common.Constants;  
  28. import com.alibaba.dubbo.common.URL;  
  29. import com.alibaba.dubbo.rpc.Invocation;  
  30. import com.alibaba.dubbo.rpc.Invoker;  
  31.   
  32. /** 
  33.  * ConsistentHashLoadBalance 
  34.  *  
  35.  * @author william.liangf 
  36.  */  
  37. public class ConsistentHashLoadBalance extends AbstractLoadBalance {  
  38.   
  39.     private final ConcurrentMap<String, ConsistentHashSelector<?>> selectors = new ConcurrentHashMap<String, ConsistentHashSelector<?>>();  
  40.   
  41.     @SuppressWarnings("unchecked")  
  42.     @Override  
  43.     protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {  
  44.         String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();  
  45.         int identityHashCode = System.identityHashCode(invokers);  
  46.         ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);  
  47.         if (selector == null || selector.getIdentityHashCode() != identityHashCode) {  
  48.             selectors.put(key, new ConsistentHashSelector<T>(invokers, invocation.getMethodName(), identityHashCode));  
  49.             selector = (ConsistentHashSelector<T>) selectors.get(key);  
  50.         }  
  51.         return selector.select(invocation);  
  52.     }  
  53.   
  54.     private static final class ConsistentHashSelector<T> {  
  55.   
  56.         private final TreeMap<Long, Invoker<T>> virtualInvokers;  
  57.   
  58.         private final int                       replicaNumber;  
  59.           
  60.         private final int                       identityHashCode;  
  61.           
  62.         private final int[]                     argumentIndex;  
  63.   
  64.         public ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {  
  65.             this.virtualInvokers = new TreeMap<Long, Invoker<T>>();  
  66.             this.identityHashCode = System.identityHashCode(invokers);  
  67.             URL url = invokers.get(0).getUrl();  
  68.             this.replicaNumber = url.getMethodParameter(methodName, "hash.nodes"160);  
  69.             String[] index = Constants.COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, "hash.arguments""0"));  
  70.             argumentIndex = new int[index.length];  
  71.             for (int i = 0; i < index.length; i ++) {  
  72.                 argumentIndex[i] = Integer.parseInt(index[i]);  
  73.             }  
  74.             for (Invoker<T> invoker : invokers) {  
  75.                 for (int i = 0; i < replicaNumber / 4; i++) {  
  76.                     byte[] digest = md5(invoker.getUrl().toFullString() + i);  
  77.                     for (int h = 0; h < 4; h++) {  
  78.                         long m = hash(digest, h);  
  79.                         virtualInvokers.put(m, invoker);  
  80.                     }  
  81.                 }  
  82.             }  
  83.         }  
  84.   
  85.         public int getIdentityHashCode() {  
  86.             return identityHashCode;  
  87.         }  
  88.   
  89.         public Invoker<T> select(Invocation invocation) {  
  90.             String key = toKey(invocation.getArguments());  
  91.             byte[] digest = md5(key);  
  92.             Invoker<T> invoker = sekectForKey(hash(digest, 0));  
  93.             return invoker;  
  94.         }  
  95.   
  96.         private String toKey(Object[] args) {  
  97.             StringBuilder buf = new StringBuilder();  
  98.             for (int i : argumentIndex) {  
  99.                 if (i >= 0 && i < args.length) {  
  100.                     buf.append(args[i]);  
  101.                 }  
  102.             }  
  103.             return buf.toString();  
  104.         }  
  105.   
  106.         private Invoker<T> sekectForKey(long hash) {  
  107.             Invoker<T> invoker;  
  108.             Long key = hash;  
  109.             if (!virtualInvokers.containsKey(key)) {  
  110.                 SortedMap<Long, Invoker<T>> tailMap = virtualInvokers.tailMap(key);  
  111.                 if (tailMap.isEmpty()) {  
  112.                     key = virtualInvokers.firstKey();  
  113.                 } else {  
  114.                     key = tailMap.firstKey();  
  115.                 }  
  116.             }  
  117.             invoker = virtualInvokers.get(key);  
  118.             return invoker;  
  119.         }  
  120.   
  121.         private long hash(byte[] digest, int number) {  
  122.             return (((long) (digest[3 + number * 4] & 0xFF) << 24)  
  123.                     | ((long) (digest[2 + number * 4] & 0xFF) << 16)  
  124.                     | ((long) (digest[1 + number * 4] & 0xFF) << 8)   
  125.                     | (digest[0 + number * 4] & 0xFF))   
  126.                     & 0xFFFFFFFFL;  
  127.         }  
  128.   
  129.         private byte[] md5(String value) {  
  130.             MessageDigest md5;  
  131.             try {  
  132.                 md5 = MessageDigest.getInstance("MD5");  
  133.             } catch (NoSuchAlgorithmException e) {  
  134.                 throw new IllegalStateException(e.getMessage(), e);  
  135.             }  
  136.             md5.reset();  
  137.             byte[] bytes = null;  
  138.             try {  
  139.                 bytes = value.getBytes("UTF-8");  
  140.             } catch (UnsupportedEncodingException e) {  
  141.                 throw new IllegalStateException(e.getMessage(), e);  
  142.             }  
  143.             md5.update(bytes);  
  144.             return md5.digest();  
  145.         }  
  146.   
  147.     }  
  148.   
  149. }  


开发快报:页面打印功能,websocket 强制下线功能,玩转websocket技术  金牌
获取【下载地址】   

0 0