1はじめに
Benpian試みは、いくつかの簡単な数学の方程式を使用して、フローチャートと一緒に私たちは何をこれらのフォールトトレラントクラスタリングアルゴリズムを整理します。
2拷問魂
- 負荷分散アルゴリズムとダボの特性についての話
- アクティブな統計的アルゴリズムの数を最小限にする方法アクティブの数であります
- 単に一貫性のハッシュアルゴリズムのあなたの理解について話
3インターフェイスの継承階層
4 RandomLoadBalance(ランダム)
ランダムセットの確率で重み付けランダム、
衝突断面積の高い確率が、コール量より大きい、より均一に、より均等に分散するだけでなく、重量上の確率権者を支持して動的に重みを調整します。
デフォルトポリシーが、私たちの理解にランダムとランダムは、彼はまた、量(重量)と呼ばれる概念を持っていたので、ランダムで、私たちはコードを見ている確率を制御するために使用され、同じではありません。
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* 此类从多个提供者中随机选择一个提供者。
* 可以为每个提供商定义权重:
* 如果权重都相同,则将使用random.nextInt(调用者数)。
* 如果权重不同,则将使用random.nextInt(w1 + w2 + ... + wn)
* 请注意,如果机器的性能优于其他机器,则可以设置更大的重量。
* 如果性能不是很好,则可以设置较小的重量。
*/
public class RandomLoadBalance extends AbstractLoadBalance {
public static final String NAME = "random";
/**
* 使用随机条件在列表之间选择一个invoker
* @param invokers 可能的invoker列表
* @param url URL
* @param invocation Invocation
* @param <T>
* @return 被选的invoker
*/
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// invoker的数量
int length = invokers.size();
// 每个 invoker 有相同权重
boolean sameWeight = true;
// 每个invoker的权重
int[] weights = new int[length];
// 第一个 invoker 的权重
int firstWeight = getWeight(invokers.get(0), invocation);
weights[0] = firstWeight;
// 权重之和
int totalWeight = firstWeight;
for (int i = 1; i < length; i++) {
int weight = getWeight(invokers.get(i), invocation);
// 保存以待后用
weights[i] = weight;
// Sum
totalWeight += weight;
if (sameWeight && weight != firstWeight) {
sameWeight = false;
}
}
if (totalWeight > 0 && !sameWeight) {
// 如果并非每个invoker都具有相同的权重且至少一个invoker的权重大于0,请根据totalWeight随机选择
int offset = ThreadLocalRandom.current().nextInt(totalWeight);
// 根据随机值返回invoker
for (int i = 0; i < length; i++) {
offset -= weights[i];
if (offset < 0) {
return invokers.get(i);
}
}
}
// 如果所有invoker都具有相同的权重值或totalWeight = 0,则平均返回。
return invokers.get(ThreadLocalRandom.current().nextInt(length));
}
}
复制代码
分析
- フローチャート
1,2,3,4であり、ノードAに対して要求の確率は1 /(1 + 2 + 4 + 3)= 10%である重みに対応する4つのクラスタは、A、B、C、Dのノードがあると仮定.B、C、D及びノードので、20%、30%、40%。
ランダムアルゴリズムは比較的容易に理解することであるが、インタビューでは、一般的にこのことを聞いていないが、我々は、同様の機能を実現したい場合は、彼はこのコードのアイデアは非常に彼がビューの純粋に数学的な観点からこのアイデアを実現参照し、まだ非常にエレガントで実現しましたよく理解され、我々はまだ前提の上に数学的分析に従っている。我々は、総重量は、次に場合、整数をランダム10に係る?ランダムにその重みを行う方法、(1 + 2 + 3 + 4)10であり、知っていますこのような2 2.ランダムターンのうち、次いで重量を引く、(乱数)1(重量Aの量)= 1、次いで1(計算ステップの結果)-2(Bの重量の重量)= -1、この場合、-1 <0で、次にBは、他のように呼び出されます
5 RoundRobinLoadBalance(ポーリング)
投票、ラウンドロビンリセット規則の重量比
第二のマシンは非常に遅いですが、第二段階ではという点で、カード上の2番目の要求に転送する場合、時間をかけて、すべての要求がカードに転送されているがハングアップしませんでした:プロバイダーが存在は、次のような問題の遅い蓄積を要求します
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* Round robin load balance.
*/
public class RoundRobinLoadBalance extends AbstractLoadBalance {
public static final String NAME = "roundrobin";
private static final int RECYCLE_PERIOD = 60000;
protected static class WeightedRoundRobin {
private int weight;
private AtomicLong current = new AtomicLong(0);
private long lastUpdate;
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
current.set(0);
}
public long increaseCurrent() {
return current.addAndGet(weight);
}
public void sel(int total) {
current.addAndGet(-1 * total);
}
public long getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(long lastUpdate) {
this.lastUpdate = lastUpdate;
}
}
private ConcurrentMap<String, ConcurrentMap<String, WeightedRoundRobin>> methodWeightMap = new ConcurrentHashMap<String, ConcurrentMap<String, WeightedRoundRobin>>();
private AtomicBoolean updateLock = new AtomicBoolean();
/**
* 获取为指定invocation缓存的invocation地址列表
* for unit test only
*/
protected <T> Collection<String> getInvokerAddrList(List<Invoker<T>> invokers, Invocation invocation) {
String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
Map<String, WeightedRoundRobin> map = methodWeightMap.get(key);
if (map != null) {
return map.keySet();
}
return null;
}
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
String key = invokers.get(0).getUrl().getServiceKey() + "." + invocation.getMethodName();
ConcurrentMap<String, WeightedRoundRobin> map = methodWeightMap.get(key);
if (map == null) {
methodWeightMap.putIfAbsent(key, new ConcurrentHashMap<String, WeightedRoundRobin>());
map = methodWeightMap.get(key);
}
int totalWeight = 0;
long maxCurrent = Long.MIN_VALUE;
long now = System.currentTimeMillis();
Invoker<T> selectedInvoker = null;
WeightedRoundRobin selectedWRR = null;
for (Invoker<T> invoker : invokers) {
String identifyString = invoker.getUrl().toIdentityString();
WeightedRoundRobin weightedRoundRobin = map.get(identifyString);
int weight = getWeight(invoker, invocation);
if (weightedRoundRobin == null) {
weightedRoundRobin = new WeightedRoundRobin();
weightedRoundRobin.setWeight(weight);
map.putIfAbsent(identifyString, weightedRoundRobin);
}
if (weight != weightedRoundRobin.getWeight()) {
//weight changed
weightedRoundRobin.setWeight(weight);
}
long cur = weightedRoundRobin.increaseCurrent();
weightedRoundRobin.setLastUpdate(now);
if (cur > maxCurrent) {
maxCurrent = cur;
selectedInvoker = invoker;
selectedWRR = weightedRoundRobin;
}
totalWeight += weight;
}
if (!updateLock.get() && invokers.size() != map.size()) {
if (updateLock.compareAndSet(false, true)) {
try {
// copy -> modify -> update reference
ConcurrentMap<String, WeightedRoundRobin> newMap = new ConcurrentHashMap<>(map);
newMap.entrySet().removeIf(item -> now - item.getValue().getLastUpdate() > RECYCLE_PERIOD);
methodWeightMap.put(key, newMap);
} finally {
updateLock.set(false);
}
}
}
if (selectedInvoker != null) {
selectedWRR.sel(totalWeight);
return selectedInvoker;
}
// should not happen here
return invokers.get(0);
}
}
复制代码
nginxの負荷分散のデフォルトはポーリングしています
6 LeastActiveLoadBalance(アクティブの最小数)
- アクティブコールの最小数は、同じ乱数がアクティブで、番号は前後にアクティブコール数の差を指します
- だから、あまり遅いプロバイダは、コールが遅くプロバイダカウントになります前と後との間に大きな差があるため、要求を受信します。
我々はA、B 2つのプロバイダを持っている場合たとえば、各サービスは、アクティブなカウンターを持っています。初期カウント0の両方の開始要求を処理するプロバイダAは、カウントが+1、この時間Aで処理されていない、あるとき要求数を処理した後-1とBは、Bは、1,0であり、その後、要求処理が急速にカウントので、この場合には、処理されていない.Bを取り扱う受信した場合に新たな要求、 Bは、これは、文書が遅いプロバイダが少ないの要求を受け、言うである(アクティブカウンタBがAよりも小さい)、プロバイダを選択します
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcStatus;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
/**
* 过滤活动调用次数最少的调用者数量,并计算这些调用者的权重和数量。
* 如果只有一个调用程序,则直接使用该调用程序;
* 如果有多个调用者并且权重不相同,则根据总权重随机;
* 如果有多个调用者且权重相同,则将其随机调用。
*/
public class LeastActiveLoadBalance extends AbstractLoadBalance {
public static final String NAME = "leastactive";
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
// invoker的总个数
int length = invokers.size();
// invoker最小的活跃数
int leastActive = -1;
// 相同最小活跃数(leastActive)的invoker个数
int leastCount = 0;
// 相同最小活跃数(leastActive)的下标
int[] leastIndexes = new int[length];
// the weight of every invokers
int[] weights = new int[length];
// 所有最不活跃invoker的预热权重之和
int totalWeight = 0;
// 第一个最不活跃的invoker的权重, 用于于计算是否相同
int firstWeight = 0;
// 每个最不活跃的调用者都具有相同的权重值?
boolean sameWeight = true;
// Filter out all the least active invokers
for (int i = 0; i < length; i++) {
Invoker<T> invoker = invokers.get(i);
// Get the active number of the invoker
int active = RpcStatus.getStatus(invoker.getUrl(), invocation.getMethodName()).getActive();
// Get the weight of the invoker's configuration. The default value is 100.
int afterWarmup = getWeight(invoker, invocation);
// save for later use
weights[i] = afterWarmup;
// If it is the first invoker or the active number of the invoker is less than the current least active number
if (leastActive == -1 || active < leastActive) {
// Reset the active number of the current invoker to the least active number
leastActive = active;
// Reset the number of least active invokers
leastCount = 1;
// Put the first least active invoker first in leastIndexes
leastIndexes[0] = i;
// Reset totalWeight
totalWeight = afterWarmup;
// Record the weight the first least active invoker
firstWeight = afterWarmup;
// Each invoke has the same weight (only one invoker here)
sameWeight = true;
// If current invoker's active value equals with leaseActive, then accumulating.
} else if (active == leastActive) {
// 记录leastIndexes order最小活跃数下标
leastIndexes[leastCount++] = i;
// 累计总权重
totalWeight += afterWarmup;
// If every invoker has the same weight?
if (sameWeight && i > 0
&& afterWarmup != firstWeight) {
sameWeight = false;
}
}
}
// Choose an invoker from all the least active invokers
if (leastCount == 1) {
// 如果只有一个最小则直接返回
return invokers.get(leastIndexes[0]);
}
if (!sameWeight && totalWeight > 0) {
// 如果权重不相同且权重大于0则按总权重数随机
int offsetWeight = ThreadLocalRandom.current().nextInt(totalWeight);
// 并确定随机值落在哪个片断上
for (int i = 0; i < leastCount; i++) {
int leastIndex = leastIndexes[i];
offsetWeight -= weights[leastIndex];
if (offsetWeight < 0) {
return invokers.get(leastIndex);
}
}
}
// 如果权重相同或权重为0则均等随机
return invokers.get(leastIndexes[ThreadLocalRandom.current().nextInt(leastCount)]);
}
}
复制代码
分析
コードのこの部分は二つの部分にまとめることになります
- アクティブと重みの統計情報の数
- インボーカを選択する。重量が一致している(同じルール参照確率的アルゴリズム上)またはleastIndexs配列から異なる場合の総重量は、ランダム呼の平等、0であれば、彼は、leastIndexsアレイにアクティブ統計の最小数呼び出しすなわちそれは問題ではない理解していない。(同じ考え方を踏襲か、確率的アルゴリズムおよび減算)重い重量の割合に基づいて呼び出し、以下のフローチャートと数学的分析を見て
- フローチャート
理論
アクティブノードの最小数のA、B、C、Dは1,1,2,3-、1,2,3,4-重量であると仮定する。するとleastIndexs(最小活性配列が配列である、アクティブAの数ので、Bのアレイの内容)が最小であり、1である[B] II.A、重量Bは、コールの確率はB 2の確率は、1 /(1 + 2)= 1/3であるように、1及び2の重量であります/ (1 + 2)= 2/3
アクティブな数の推移org.apache.dubbo.rpc.filter.ActiveLimitFilter
構成されていない場合はプロパティを、デフォルト数は+1を呼び出す前にアクティブで、-1私は、文書のスクリーンショットを掲載置くように、呼の終了を考慮して、多くの人がこのプロパティを使用していないかもしれませんdubbo:reference
actives
また、その負荷の使用は、アルゴリズムのバランスをとるならば、あなたはdubbo:service
また、設定する必要がありますfilter="activelimit"
7 ConsistentHashLoadBalance(一貫したハッシング)
- 一貫性要求ハッシュ、同じパラメータは常に同じプロバイダに送信されます
- ステーションは、プロバイダにリンクされている場合は、元の要求は、他のプロバイダに等しい株式で、うではない劇的な変化原因、仮想ノードに基づいて、プロバイダに送信しました。
- 推奨読書
http://en.wikipedia.org/wiki/Consistent_hashing
デフォルトでは最初の引数のハッシュ、変更したい場合は、configure
<dubbo:parameter key="hash.arguments" value="0,1" />复制代码
160部、修正したい場合は、configureとデフォルトの仮想ノード
<dubbo:parameter key="hash.nodes" value="320" />复制代码
package org.apache.dubbo.rpc.cluster.loadbalance;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
public class ConsistentHashLoadBalance extends AbstractLoadBalance {
public static final String NAME = "consistenthash";
/**
* Hash nodes name
*/
public static final String HASH_NODES = "hash.nodes";
/**
* Hash arguments name
*/
public static final String HASH_ARGUMENTS = "hash.arguments";
private final ConcurrentMap<String, ConsistentHashSelector<?>> selectors = new ConcurrentHashMap<String, ConsistentHashSelector<?>>();
@SuppressWarnings("unchecked")
@Override
protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) {
String methodName = RpcUtils.getMethodName(invocation);
String key = invokers.get(0).getUrl().getServiceKey() + "." + methodName;
int identityHashCode = System.identityHashCode(invokers);
ConsistentHashSelector<T> selector = (ConsistentHashSelector<T>) selectors.get(key);
if (selector == null || selector.identityHashCode != identityHashCode) {
selectors.put(key, new ConsistentHashSelector<T>(invokers, methodName, identityHashCode));
selector = (ConsistentHashSelector<T>) selectors.get(key);
}
return selector.select(invocation);
}
private static final class ConsistentHashSelector<T> {
private final TreeMap<Long, Invoker<T>> virtualInvokers;
private final int replicaNumber;
private final int identityHashCode;
private final int[] argumentIndex;
ConsistentHashSelector(List<Invoker<T>> invokers, String methodName, int identityHashCode) {
this.virtualInvokers = new TreeMap<Long, Invoker<T>>();
this.identityHashCode = identityHashCode;
URL url = invokers.get(0).getUrl();
this.replicaNumber = url.getMethodParameter(methodName, HASH_NODES, 160);
String[] index = COMMA_SPLIT_PATTERN.split(url.getMethodParameter(methodName, HASH_ARGUMENTS, "0"));
argumentIndex = new int[index.length];
for (int i = 0; i < index.length; i++) {
argumentIndex[i] = Integer.parseInt(index[i]);
}
for (Invoker<T> invoker : invokers) {
String address = invoker.getUrl().getAddress();
for (int i = 0; i < replicaNumber / 4; i++) {
byte[] digest = md5(address + i);
for (int h = 0; h < 4; h++) {
long m = hash(digest, h);
virtualInvokers.put(m, invoker);
}
}
}
}
public Invoker<T> select(Invocation invocation) {
String key = toKey(invocation.getArguments());
byte[] digest = md5(key);
return selectForKey(hash(digest, 0));
}
private String toKey(Object[] args) {
StringBuilder buf = new StringBuilder();
for (int i : argumentIndex) {
if (i >= 0 && i < args.length) {
buf.append(args[i]);
}
}
return buf.toString();
}
private Invoker<T> selectForKey(long hash) {
Map.Entry<Long, Invoker<T>> entry = virtualInvokers.ceilingEntry(hash);
if (entry == null) {
entry = virtualInvokers.firstEntry();
}
return entry.getValue();
}
private long hash(byte[] digest, int number) {
return (((long) (digest[3 + number * 4] & 0xFF) << 24)
| ((long) (digest[2 + number * 4] & 0xFF) << 16)
| ((long) (digest[1 + number * 4] & 0xFF) << 8)
| (digest[number * 4] & 0xFF))
& 0xFFFFFFFFL;
}
private byte[] md5(String value) {
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e.getMessage(), e);
}
md5.reset();
byte[] bytes = value.getBytes(StandardCharsets.UTF_8);
md5.update(bytes);
return md5.digest();
}
}
}
复制代码
アルゴリズムのコードの実装、その後、主に3つのキーワード、原則、影響マシンダウン、仮想ノードについて、より大きな空間的に思い付きます
原則
時間に、私たちは時計を持っていることを、時計上の各サーバノードのマッピングを想定しているだけで、キーは、瞬間を見るためにマップされ、その後、キーを時計回りに取り、遭遇した最初のノードは、私たちに必要なことでしたサーバーノードを探して
我々はまだ持っている場合は、B、C、Dの4つのノード(場合記事全体の感触が....これをやっている)、私たちはそれぞれ0,3,6,9、整数にルールターンのいくつかの種類を介してそれらを置きます。したがって、以下クロック分布に応じ
一定のルールにより、主要な仮定は、1に変換し、最初のノードは、彼が遭遇した時計回りであること、bは、bが、我々が探しているノードであります
あなたはユニークな整数そのスティックに異なるノード名の対応を行うことができれば、このルールは、あなたがあなた自身を設計しますが、別のノード名、整数等しい確率に変換することを認識することができ、このルールの品質の尺度でありますダ・バー。もちろん、JavaのCRC32の内側に、このクラスでは、あなたは見つけることができます。
ここでは、クロックは、どのようにケースのフィット感に行うために別の質問、ポイントの数が限られているかもしれません
実際には、この時計は、我々はそれを理解してやるだけの便利な比喩で、実際には、我々は下にインストールすることができ、リング[0,2 ^ 32-1]の数字、この世界的なサーバーの大きさに分散することができます。
マシンダウンの影響
bノードがハングアップしたときにグラフにより、我々は、時計回りの規則に従って、ターゲットノードがCである、すなわち、それを見ることができる、唯一つのノードに影響し、他のノードは影響を受けません。
ポーリングアルゴリズムがモジュロであれば、N-1セットからNサーバを言って、ヒット率は、1 /(N-1)になり、より多くのサーバー、大きな影響はそう。
仮想ノード
、B、C、Dの4つのノードを持つ仮想ノードの概念を持っている?我々はまだ最初の仮定に戻って、我々はまだ、彼らは、この自然の法則により形質転換されたのはなぜ0,3,6,9にあります均一な。しかし、どのような場合、これは0,1,2,3であり、それは非常に不均一である。我々は仮想ノードを導入する必要があるので、実際には、リング上のノードをマッピングするための一般的なハッシュ関数は、一様ではなく、その仮想ノードそれは何ですか?
N実際のノードがある場合、各実ノードはM個の仮想ノードにマッピングされ、次いで、M * Nの仮想ノードの、実際の仮想分散ノードに各ノードの対応するハッシュ、リング内の実ノードを方法を互い違いダウンした後、他のすべてのノードに等しい株式に彼らの影響力を入れました。
すなわち、仮想ノードA0、A1、A2、B0、B1、B2、C0、C1、C2、D0、D1、D2次にC0、下のノードCを想定し、リング上の散乱のA、B、C、D、 C1、C2は、図以下圧力伝達D0、A1、B1、です。
参照
- https://www.jianshu.com/p/53feb7f5f5d9
- ダボ公式サイト
すべての乾燥技術の公衆番号へようこそ注意:JavaEdge